There are a lot of different data structures in Python, such as list,tuple,set,dic, why do I have to speak set alone?
Because set is a relatively easy-to-forget data structure, not only in Python, but also in C + +, I rarely use set anyway. But after using it, I found the set is actually very powerful. Here are some useful examples of set comparison:
Find the same data in two lists
The first reaction is to traverse a list, get all the data, and then judge it in the second column. The code is as follows:
def Main (): list1=[1,2,3,4,5] list2=[3,4,5,6,7] list3=[] for in list1: if in list2: list3.append (each) Print List3 if __name__ ' __main__ ' : main ()
If you use set, it is easy to use intersetion (), it can get the intersection of two set
def Main (): list1=[1,2,3,4,5] list2=[3,4,5,6,7] s1,s2=Set (List1), set ( LIST2) list3=list (s1.intersection (S2)) print list3if __name__ ' __main__ ' : main ()
The same approach would be:
S1.union (S2), which is used to get the set of two sets. That is, the collection of all the elements in the two list.
S1.difference (S2), which is used to get the difference set of two set. That is, a collection that exists in S1 but does not exist in the S2.
S1.symmetric_difference (S2), which is equivalent to s1.union (S2)-s1.intersection (S2). That is, the collection of elements that are not duplicated in S1 and S2.
The use of set in Python