def diff (Lista,listb): #求交集的两种方式 Reta = [i-I in ListA if I in Listb] Retb = List (set (ListA). Intersection (Set (LISTB))) Print "Reta is:", Reta print "Retb are:", retb #求并集 retc = List (set (ListA))) print "Listb is:", retC1 #求差集, In B but not within a retd = List (set (LISTB)). Difference (set (ListA))) print "Retd is:", retd RetE = [i-I in Listb if I not in ListA] Print "RetE is:", Retedef Main (): ListA = [1,2,3,4,5] Listb = [3,4,5,6,7] diff (lista,listb) if __name__ = = ' __main__ ': Mai N () 1234567891011121314151617181920212223242526272829303132333435 let code run up Reta is: [3, 4, 5]retb are: [3, 4, 5]RETC1 is: [1, 2, 3, 4, 5, 6, 7]retd is: [6, 7]rete is: [6, 7]12345 in combination with the code, there are basically two ideas: 1. Use list parsing. List parsing is generally faster than looping, and more pythonic looks more awesome. 2. After the list is converted to set, the various methods of set are used to deal with it.
Python two list intersection, set, difference set