Implementation of the list in Python subtraction operation introduction _python

Source: Internet
Author: User

Question Description: Suppose I have such two list,

One is list1,list1 = [1, 2, 3, 4, 5]
One is list2,list2 = [1, 4, 5]
How do we get a new list,list3,
The LIST3 includes all elements in the list1 that are not present in the List2.
namely: List3 = List1–list2

Solution:We can use the set (set) operation
LIST3 = List (set (List1) –set (LIST2))

The set operation converts a list into a collection.
Hypothesis: list_t = [1, 2, 3, 1]
So: List (set (list_t)) = [1, 2, 3]
Yes, duplicate items will be deleted.

Other scenarios:list3 = [I for I-list1 if I not in List2] #可用于list分片
This is also very intuitive to write.
But when the list is large, there is no set method fast.

Extra Knowledge:a = [[I,j] for I in range (2) for J in Range (3)]
This is very similar to "other schemes",
are judged and calculated in [].
Feel very convenient, at least more convenient, faster than the following:
A = []
For I in range (2):
For j in Range (3):
A.append ([i,j])

Some questions: if list_tmp = [[1,2],[2,3]]
The list is not composed of individual elements, but list,
Then set (LIST_TMP) will go wrong.

also to study:hash function

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.