Python two list intersection, set, difference set

Source: Internet
Author: User

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

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.