我在Python中有两个列表:
temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two']
假设每个列表中的元素都是唯一的,我想用第一个列表中的项创建第三个列表,这些项不在第二个列表中:
temp3 = ['Three', 'Four']
有没有没有周期和检查的快速方法?
我在Python中有两个列表:
temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two']
假设每个列表中的元素都是唯一的,我想用第一个列表中的项创建第三个列表,这些项不在第二个列表中:
temp3 = ['Three', 'Four']
有没有没有周期和检查的快速方法?
当前回答
如果你遇到TypeError: unhashable type: 'list',你需要将列表或集转换为元组。
set(map(tuple, list_of_lists1)).symmetric_difference(set(map(tuple, list_of_lists2)))
参见如何比较python中的列表/集列表?
其他回答
如果您想要更类似于变更集的东西……可以使用Counter
from collections import Counter
def diff(a, b):
""" more verbose than needs to be, for clarity """
ca, cb = Counter(a), Counter(b)
to_add = cb - ca
to_remove = ca - cb
changes = Counter(to_add)
changes.subtract(to_remove)
return changes
lista = ['one', 'three', 'four', 'four', 'one']
listb = ['one', 'two', 'three']
In [127]: diff(lista, listb)
Out[127]: Counter({'two': 1, 'one': -1, 'four': -2})
# in order to go from lista to list b, you need to add a "two", remove a "one", and remove two "four"s
In [128]: diff(listb, lista)
Out[128]: Counter({'four': 2, 'one': 1, 'two': -1})
# in order to go from listb to lista, you must add two "four"s, add a "one", and remove a "two"
def diffList(list1, list2): # returns the difference between two lists.
if len(list1) > len(list2):
return (list(set(list1) - set(list2)))
else:
return (list(set(list2) - set(list1)))
例如,如果list1 =[10, 15, 20, 25, 30, 35, 40]和list2 =[25, 40, 35],那么返回的列表将输出= [10,20,30,15]
由于目前的解决方案都不产生一个元组,我将抛出:
temp3 = tuple(set(temp1) - set(temp2))
另外:
#edited using @Mark Byers idea. If you accept this one as answer, just accept his instead.
temp3 = tuple(x for x in temp1 if x not in set(temp2))
像其他在这个方向上得到答案的非元组一样,它保持了顺序
你可以使用列表推导式:
temp3 = [item for item in temp1 if item not in temp2]
单线版arulmr解决方案
def diff(listA, listB):
return set(listA) - set(listB) | set(listB) -set(listA)