我在Python中有两个列表:
temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two']
假设每个列表中的元素都是唯一的,我想用第一个列表中的项创建第三个列表,这些项不在第二个列表中:
temp3 = ['Three', 'Four']
有没有没有周期和检查的快速方法?
我在Python中有两个列表:
temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two']
假设每个列表中的元素都是唯一的,我想用第一个列表中的项创建第三个列表,这些项不在第二个列表中:
temp3 = ['Three', 'Four']
有没有没有周期和检查的快速方法?
当前回答
以下是@SuperNova的回答的修改版本
def get_diff(a: list, b: list) -> list:
return list(set(a) ^ set(b))
其他回答
这里有一个最简单情况的反答案。
这比上面那个做双向差分的要短,因为它只做了问题要求的事情:生成第一个列表中的东西的列表,而不是第二个列表中的东西。
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']
以下是@SuperNova的回答的修改版本
def get_diff(a: list, b: list) -> list:
return list(set(a) ^ set(b))
这是另一个解决方案:
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
这里有一个简单的方法来区分两个列表(无论内容是什么),你可以得到如下所示的结果:
>>> from sets import Set
>>>
>>> l1 = ['xvda', False, 'xvdbb', 12, 'xvdbc']
>>> l2 = ['xvda', 'xvdbb', 'xvdbc', 'xvdbd', None]
>>>
>>> Set(l1).symmetric_difference(Set(l2))
Set([False, 'xvdbd', None, 12])
希望这对你有所帮助。
我知道这个问题已经得到了很好的答案,但我希望使用numpy添加以下方法。
temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two']
list(np.setdiff1d(temp1,temp2))
['Four', 'Three'] #Output