我在Python中有两个列表:

temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two']

假设每个列表中的元素都是唯一的,我想用第一个列表中的项创建第三个列表,这些项不在第二个列表中:

temp3 = ['Three', 'Four']

有没有没有周期和检查的快速方法?


当前回答

这里有一些简单的、保持顺序的方法来区分两个字符串列表。

Code

使用pathlib的一个不寻常的方法:

import pathlib


temp1 = ["One", "Two", "Three", "Four"]
temp2 = ["One", "Two"]

p = pathlib.Path(*temp1)
r = p.relative_to(*temp2)
list(r.parts)
# ['Three', 'Four']

这假设两个列表包含相同开头的字符串。更多细节请参阅文档。注意,与set操作相比,它不是特别快。


使用itertools.zip_longest的直接实现:

import itertools as it


[x for x, y in it.zip_longest(temp1, temp2) if x != y]
# ['Three', 'Four']

其他回答

由于目前的解决方案都不产生一个元组,我将抛出:

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 = set(temp1) - set(temp2)

获取在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]))。

如果散差表的元素是排序和集合的,你可以使用朴素方法。

list1=[1,2,3,4,5]
list2=[1,2,3]

print list1[len(list2):]

或者使用本机set方法:

subset=set(list1).difference(list2)

print subset

import timeit
init = 'temp1 = list(range(100)); temp2 = [i * 2 for i in range(50)]'
print "Naive solution: ", timeit.timeit('temp1[len(temp2):]', init, number = 100000)
print "Native set solution: ", timeit.timeit('set(temp1).difference(temp2)', init, number = 100000)

朴素解:0.0787101593292

本机集解决方案:0.998837615564

可以使用python的XOR运算符来完成。

这将删除每个列表中的重复项 这将显示temp1与temp2和temp2与temp1的差异。


set(temp1) ^ set(temp2)