Get difference between two lists

前端 未结 27 2802
傲寒
傲寒 2020-11-21 11:36

I have two lists in Python, like these:

temp1 = [\'One\', \'Two\', \'Three\', \'Four\']
temp2 = [\'One\', \'Two\']

I need to create a third

27条回答
  •  盖世英雄少女心
    2020-11-21 11:51

    I prefer to use converting to sets and then using the "difference()" function. The full code is :

    temp1 = ['One', 'Two', 'Three', 'Four'  ]                   
    temp2 = ['One', 'Two']
    set1 = set(temp1)
    set2 = set(temp2)
    set3 = set1.difference(set2)
    temp3 = list(set3)
    print(temp3)
    
    

    Output:

    >>>print(temp3)
    ['Three', 'Four']
    

    It's the easiest to undersand, and morover in future if you work with large data, converting it to sets will remove duplicates if duplicates are not required. Hope it helps ;-)

提交回复
热议问题