我在Python中有两个列表:
temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two']
假设每个列表中的元素都是唯一的,我想用第一个列表中的项创建第三个列表,这些项不在第二个列表中:
temp3 = ['Three', 'Four']
有没有没有周期和检查的快速方法?
我在Python中有两个列表:
temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two']
假设每个列表中的元素都是唯一的,我想用第一个列表中的项创建第三个列表,这些项不在第二个列表中:
temp3 = ['Three', 'Four']
有没有没有周期和检查的快速方法?
当前回答
这是另一个解决方案:
def diff(a, b):
xa = [i for i in set(a) if i not in b]
xb = [i for i in set(b) if i not in a]
return xa + xb
其他回答
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]
获取在temp1中而不在temp2中的元素 (假设每个列表中的元素是唯一的):
In [5]: list(set(temp1) - set(temp2))
Out[5]: ['Four', 'Three']
注意它是不对称的 :
In [5]: set([1, 2]) - set([2, 3])
Out[5]: set([1])
这里您可能期望/希望它等于set([1,3])。如果你想要set([1,3])作为你的答案,你可以使用set([1,2])。symmetric_difference(设置([2、3]))。
如果您想要更类似于变更集的东西……可以使用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"
这里有一个最简单情况的反答案。
这比上面那个做双向差分的要短,因为它只做了问题要求的事情:生成第一个列表中的东西的列表,而不是第二个列表中的东西。
from collections import Counter
lst1 = ['One', 'Two', 'Three', 'Four']
lst2 = ['One', 'Two']
c1 = Counter(lst1)
c2 = Counter(lst2)
diff = list((c1 - c2).elements())
或者,根据你的可读性偏好,它可以是一个不错的单行代码:
diff = list((Counter(lst1) - Counter(lst2)).elements())
输出:
['Three', 'Four']
请注意,如果您只是对其进行迭代,则可以删除list(…)调用。
因为这个解决方案使用计数器,所以相对于许多基于集合的答案,它可以正确地处理数量。例如,在这个输入中:
lst1 = ['One', 'Two', 'Two', 'Two', 'Three', 'Three', 'Four']
lst2 = ['One', 'Two']
输出结果为:
['Two', 'Two', 'Three', 'Three', 'Four']
您可以循环遍历第一个列表,对于不在第二个列表中但在第一个列表中的每一项,将其添加到第三个列表中。例句:
temp3 = []
for i in temp1:
if i not in temp2:
temp3.append(i)
print(temp3)