我在Python中有两个列表,如下所示:
temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two']我需要用第一个列表中没有出现在第二个列表中的条目创建第三个列表。从这个例子中,我必须得到
temp3 = ['Three', 'Four']有没有不需要循环和检查的快速方法?
发布于 2015-12-18 06:20:50
如果你想要更像变更集的东西...可以使用计数器
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"https://stackoverflow.com/questions/3462143
复制相似问题