获取两个列表之间的不同项,这些项是唯一的。

1230

我在Python中有两个列表:

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

假设每个列表中的元素都是唯一的,我希望创建第三个列表,其中包含第一个列表中不在第二个列表中的项目:

假设每个列表中的元素都是唯一的,我想要创建一个新的列表,其中包含来自第一个列表的但不在第二个列表中的项目:

temp3 = ['Three', 'Four']

有没有不需要循环和检查的快速方式?


26
元素是否保证唯一?如果你有 temp1 = ['One', 'One', 'One']temp2 = ['One'],你希望得到 ['One', 'One'] 还是 [] - Michael Mrozek
1
@michael-mrozek 他们是独一无二的。 - Max Frai
19
你想保留元素的顺序吗? - Mark Byers
1
这个回答解决了您的问题吗?查找不在列表中的元素 - Gonçalo Peres
33个回答

4
如果您想从列表 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]

或者

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

4

我知道这个问题已经有很好的答案了,但是我希望添加以下使用 numpy 的方法。

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

list(np.setdiff1d(temp1,temp2))

['Four', 'Three'] #Output

4

4

我更喜欢使用转换为集合,然后使用 "difference()" 函数的方法。完整代码如下:

temp1 = ['One', 'Two', 'Three', 'Four'  ]                   
temp2 = ['One', 'Two']
set1 = set(temp1)
set2 = set(temp2)
set3 = set1.difference(set2)
temp3 = list(set3)
print(temp3)

输出:

>>>print(temp3)
['Three', 'Four']

这是最容易理解的,而且如果未来你要处理大量数据,把它转换成集合将会去除重复项(如果不需要重复项的话)。希望有所帮助;-)


1
差分函数与已接受的答案中显示的“-”运算符相同,因此不确定这是否会在10年后增加任何新信息。 - OneCricketeer

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"

3
我们可以计算列表的交集减去并集:
temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two', 'Five']

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

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

2
这可以用一行代码解决。问题是给定两个列表(temp1和temp2),返回它们的差异在第三个列表(temp3)中。
temp3 = list(set(temp1).difference(set(temp2)))

1
以下是一种简单的区分两个列表(无论内容如何)的方法,您可以得到如下所示的结果:
>>> 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])

希望这对你有所帮助。

0
如果列表是对象而不是原始类型,这是一种实现方式。
代码更加明确并提供了一个副本。 这可能不是一个高效的实现,但对于较小的对象列表来说很干净。
a = [
    {'id1': 1, 'id2': 'A'},
    {'id1': 1, 'id2': 'B'},
    {'id1': 1, 'id2': 'C'},  # out
    {'id1': 2, 'id2': 'A'},
    {'id1': 2, 'id2': 'B'},  # out
]
b = [
    {'id1': 1, 'id2': 'A'},
    {'id1': 1, 'id2': 'B'},
    {'id1': 2, 'id2': 'A'},
]


def difference(a, b):
  for x in a:
    for y in b:
      if x['id1'] == y['id1'] and x['id2'] == y['id2']:
        x['is_removed'] = True

  c = [x for x in a if not x.get('is_removed', False)]
  return c


print(difference(a, b))

0

你可以遍历第一个列表,并且对于每个不在第二个列表中但在第一个列表中的项目,将其添加到第三个列表中。例如:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接