Get difference between two lists

前端 未结 27 3210
傲寒
傲寒 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:42

    The difference between two lists (say list1 and list2) can be found using the following simple function.

    def diff(list1, list2):
        c = set(list1).union(set(list2))  # or c = set(list1) | set(list2)
        d = set(list1).intersection(set(list2))  # or d = set(list1) & set(list2)
        return list(c - d)
    

    or

    def diff(list1, list2):
        return list(set(list1).symmetric_difference(set(list2)))  # or return list(set(list1) ^ set(list2))
    

    By Using the above function, the difference can be found using diff(temp2, temp1) or diff(temp1, temp2). Both will give the result ['Four', 'Three']. You don't have to worry about the order of the list or which list is to be given first.

    Python doc reference

提交回复
热议问题