我在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 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]
我知道这个问题已经有很好的答案了,但是我希望添加以下使用 numpy
的方法。
temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two']
list(np.setdiff1d(temp1,temp2))
['Four', 'Three'] #Output
如果你遇到了TypeError: unhashable type: 'list'
的错误,你需要将列表或集合转换为元组,例如:
set(map(tuple, list_of_lists1)).symmetric_difference(set(map(tuple, list_of_lists2)))
我更喜欢使用转换为集合,然后使用 "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']
这是最容易理解的,而且如果未来你要处理大量数据,把它转换成集合将会去除重复项(如果不需要重复项的话)。希望有所帮助;-)
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"
temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two', 'Five']
set(temp1+temp2)-(set(temp1)&set(temp2))
Out: set(['Four', 'Five', 'Three'])
temp3 = list(set(temp1).difference(set(temp2)))
>>> 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])
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))
你可以遍历第一个列表,并且对于每个不在第二个列表中但在第一个列表中的项目,将其添加到第三个列表中。例如:
temp3 = []
for i in temp1:
if i not in temp2:
temp3.append(i)
print(temp3)
temp1 = ['One', 'One', 'One']
和temp2 = ['One']
,你希望得到['One', 'One']
还是[]
? - Michael Mrozek