我在Python中有两个列表:

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

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

temp3 = ['Three', 'Four']

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


当前回答

我想要一个能够使用两个列表并能做diff in bash所做的事情的东西。因为当你搜索“python diff two lists”时,这个问题首先会弹出,而且不是很具体,所以我会把我想到的贴出来。

使用difflib中的SequenceMather,你可以像diff一样比较两个列表。其他答案都不会告诉你差异发生的位置,但这个答案可以。有些答案只给出了一个方向上的差异。有些元素会重新排序。有些公司不处理副本。但是这个解决方案让你在两个列表之间有了真正的区别:

a = 'A quick fox jumps the lazy dog'.split()
b = 'A quick brown mouse jumps over the dog'.split()

from difflib import SequenceMatcher

for tag, i, j, k, l in SequenceMatcher(None, a, b).get_opcodes():
  if tag == 'equal': print('both have', a[i:j])
  if tag in ('delete', 'replace'): print('  1st has', a[i:j])
  if tag in ('insert', 'replace'): print('  2nd has', b[k:l])

这个输出:

both have ['A', 'quick']
  1st has ['fox']
  2nd has ['brown', 'mouse']
both have ['jumps']
  2nd has ['over']
both have ['the']
  1st has ['lazy']
both have ['dog']

当然,如果您的应用程序做出了与其他答案相同的假设,那么您将从中受益最大。但如果你正在寻找一个真正的差异功能,那么这是唯一的方法。

例如,其他答案都无法处理:

a = [1,2,3,4,5]
b = [5,4,3,2,1]

但这一个有:

  2nd has [5, 4, 3, 2]
both have [1]
  1st has [2, 3, 4, 5]

其他回答

如果要删除列表a中存在于列表b中的所有值。

def list_diff(a, b):
    r = []

    for i in a:
        if i not in b:
            r.append(i)
    return r

list_diff([1、2、2],[1])

结果(2,2):

or

def list_diff(a, b):
    return [x for x in a if x not in b]

您可以循环遍历第一个列表,对于不在第二个列表中但在第一个列表中的每一项,将其添加到第三个列表中。例句:

temp3 = []
for i in temp1:
    if i not in temp2:
        temp3.append(i)
print(temp3)

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

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))

像其他在这个方向上得到答案的非元组一样,它保持了顺序

我想要一个能够使用两个列表并能做diff in bash所做的事情的东西。因为当你搜索“python diff two lists”时,这个问题首先会弹出,而且不是很具体,所以我会把我想到的贴出来。

使用difflib中的SequenceMather,你可以像diff一样比较两个列表。其他答案都不会告诉你差异发生的位置,但这个答案可以。有些答案只给出了一个方向上的差异。有些元素会重新排序。有些公司不处理副本。但是这个解决方案让你在两个列表之间有了真正的区别:

a = 'A quick fox jumps the lazy dog'.split()
b = 'A quick brown mouse jumps over the dog'.split()

from difflib import SequenceMatcher

for tag, i, j, k, l in SequenceMatcher(None, a, b).get_opcodes():
  if tag == 'equal': print('both have', a[i:j])
  if tag in ('delete', 'replace'): print('  1st has', a[i:j])
  if tag in ('insert', 'replace'): print('  2nd has', b[k:l])

这个输出:

both have ['A', 'quick']
  1st has ['fox']
  2nd has ['brown', 'mouse']
both have ['jumps']
  2nd has ['over']
both have ['the']
  1st has ['lazy']
both have ['dog']

当然,如果您的应用程序做出了与其他答案相同的假设,那么您将从中受益最大。但如果你正在寻找一个真正的差异功能,那么这是唯一的方法。

例如,其他答案都无法处理:

a = [1,2,3,4,5]
b = [5,4,3,2,1]

但这一个有:

  2nd has [5, 4, 3, 2]
both have [1]
  1st has [2, 3, 4, 5]

我们可以计算交集减去列表并集:

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

set(temp1+temp2)-(set(temp1)&set(temp2))

Out: set(['Four', 'Five', 'Three'])