获取两个具有唯一条目的列表之间的差异
- 2024-11-26 08:36:00
- admin 原创
- 161
问题描述:
我在 Python 中有两个列表:
temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two']
假设每个列表中的元素都是唯一的,我想创建第三个列表,其中包含第一个列表中但不在第二个列表中的项目:
temp3 = ['Three', 'Four']
有没有无需循环和检查的快速方法?
解决方案 1:
获取在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(set([2, 3]))
。
解决方案 2:
现有的解决方案都提供以下其中一种:
比 O(n*m) 性能更快。
保留输入列表的顺序。
但目前还没有解决方案可以同时满足这两种需求。如果你想同时满足这两种需求,可以尝试以下方法:
s = set(temp2)
temp3 = [x for x in temp1 if x not in s]
性能测试
import timeit
init = 'temp1 = list(range(100)); temp2 = [i * 2 for i in range(50)]'
print timeit.timeit('list(set(temp1) - set(temp2))', init, number = 100000)
print timeit.timeit('s = set(temp2);[x for x in temp1 if x not in s]', init, number = 100000)
print timeit.timeit('[item for item in temp1 if item not in temp2]', init, number = 100000)
结果:
4.34620224079 # ars' answer
4.2770634955 # This answer
30.7715615392 # matt b's answer
我介绍的方法除了保持顺序之外,还(稍微)比集合减法快,因为它不需要构造不必要的集合。如果第一个列表比第二个列表长得多,并且散列成本高昂,则性能差异会更加明显。以下是第二个测试,演示了这一点:
init = '''
temp1 = [str(i) for i in range(100000)]
temp2 = [str(i * 2) for i in range(50)]
'''
结果:
11.3836875916 # ars' answer
3.63890368748 # this answer (3 times faster!)
37.7445402279 # matt b's answer
解决方案 3:
可以使用 python XOR 运算符完成。
这将删除每个列表中的重复项
这将显示 temp1 与 temp2 以及 temp2 与 temp1 的差异。
set(temp1) ^ set(temp2)
解决方案 4:
您可以使用列表理解:
temp3 = [item for item in temp1 if item not in temp2]
解决方案 5:
尝试一下:
temp3 = set(temp1) - set(temp2)
解决方案 6:
如果你想要递归地获得差异,我已经为 python 编写了一个包:
https ://github.com/seperman/deepdiff
安装
从 PyPi 安装:
pip install deepdiff
示例用法
输入
>>> from deepdiff import DeepDiff
>>> from pprint import pprint
>>> from __future__ import print_function # In case running on Python 2
同一对象返回空
>>> t1 = {1:1, 2:2, 3:3}
>>> t2 = t1
>>> print(DeepDiff(t1, t2))
{}
商品类型已改变
>>> t1 = {1:1, 2:2, 3:3}
>>> t2 = {1:1, 2:"2", 3:3}
>>> pprint(DeepDiff(t1, t2), indent=2)
{ 'type_changes': { 'root[2]': { 'newtype': <class 'str'>,
'newvalue': '2',
'oldtype': <class 'int'>,
'oldvalue': 2}}}
物品价值已改变
>>> t1 = {1:1, 2:2, 3:3}
>>> t2 = {1:1, 2:4, 3:3}
>>> pprint(DeepDiff(t1, t2), indent=2)
{'values_changed': {'root[2]': {'newvalue': 4, 'oldvalue': 2}}}
添加和/或移除商品
>>> t1 = {1:1, 2:2, 3:3, 4:4}
>>> t2 = {1:1, 2:4, 3:3, 5:5, 6:6}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff)
{'dic_item_added': ['root[5]', 'root[6]'],
'dic_item_removed': ['root[4]'],
'values_changed': {'root[2]': {'newvalue': 4, 'oldvalue': 2}}}
字符串差异
>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world"}}
>>> t2 = {1:1, 2:4, 3:3, 4:{"a":"hello", "b":"world!"}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'values_changed': { 'root[2]': {'newvalue': 4, 'oldvalue': 2},
"root[4]['b']": { 'newvalue': 'world!',
'oldvalue': 'world'}}}
字符串差异2
>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world!
Goodbye!
1
2
End"}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world
1
2
End"}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'values_changed': { "root[4]['b']": { 'diff': '---
'
'+++
'
'@@ -1,5 +1,4 @@
'
'-world!
'
'-Goodbye!
'
'+world
'
' 1
'
' 2
'
' End',
'newvalue': 'world
1
2
End',
'oldvalue': 'world!
'
'Goodbye!
'
'1
'
'2
'
'End'}}}
>>>
>>> print (ddiff['values_changed']["root[4]['b']"]["diff"])
---
+++
@@ -1,5 +1,4 @@
-world!
-Goodbye!
+world
1
2
End
类型更改
>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world
End"}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'type_changes': { "root[4]['b']": { 'newtype': <class 'str'>,
'newvalue': 'world
End',
'oldtype': <class 'list'>,
'oldvalue': [1, 2, 3]}}}
列表差异
>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3, 4]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2]}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{'iterable_item_removed': {"root[4]['b'][2]": 3, "root[4]['b'][3]": 4}}
列出差异2:
>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 3, 2, 3]}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'iterable_item_added': {"root[4]['b'][3]": 3},
'values_changed': { "root[4]['b'][1]": {'newvalue': 3, 'oldvalue': 2},
"root[4]['b'][2]": {'newvalue': 2, 'oldvalue': 3}}}
列出忽略顺序或重复的差异:(使用与上面相同的词典)
>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 3, 2, 3]}}
>>> ddiff = DeepDiff(t1, t2, ignore_order=True)
>>> print (ddiff)
{}
包含字典的列表:
>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, {1:1, 2:2}]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, {1:3}]}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'dic_item_removed': ["root[4]['b'][2][2]"],
'values_changed': {"root[4]['b'][2][1]": {'newvalue': 3, 'oldvalue': 1}}}
套:
>>> t1 = {1, 2, 8}
>>> t2 = {1, 2, 3, 5}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (DeepDiff(t1, t2))
{'set_item_added': ['root[3]', 'root[5]'], 'set_item_removed': ['root[8]']}
命名元组:
>>> from collections import namedtuple
>>> Point = namedtuple('Point', ['x', 'y'])
>>> t1 = Point(x=11, y=22)
>>> t2 = Point(x=11, y=23)
>>> pprint (DeepDiff(t1, t2))
{'values_changed': {'root.y': {'newvalue': 23, 'oldvalue': 22}}}
自定义对象:
>>> class ClassA(object):
... a = 1
... def __init__(self, b):
... self.b = b
...
>>> t1 = ClassA(1)
>>> t2 = ClassA(2)
>>>
>>> pprint(DeepDiff(t1, t2))
{'values_changed': {'root.b': {'newvalue': 2, 'oldvalue': 1}}}
添加的对象属性:
>>> t2.c = "new attribute"
>>> pprint(DeepDiff(t1, t2))
{'attribute_added': ['root.c'],
'values_changed': {'root.b': {'newvalue': 2, 'oldvalue': 1}}}
解决方案 7:
可以使用以下简单函数找到两个列表(例如 list1 和 list2)之间的差异。
def diff(list1, list2):
c = set(list1).union(set(list2)) # or c = set(list1) | set(list2)
d = set(list1).intersection(set(list2)) # or d = set(list1) & set(list2)
return list(c - d)
或者
def diff(list1, list2):
return list(set(list1).symmetric_difference(set(list2))) # or return list(set(list1) ^ set(list2))
diff(temp2, temp1)
通过使用上述函数,可以使用或找到差异diff(temp1, temp2)
。两者都会给出结果['Four', 'Three']
。您不必担心列表的顺序或首先给出哪个列表。
Python 文档参考
解决方案 8:
最简单的方法,
使用set().difference(set())
list_a = [1,2,3]
list_b = [2,3]
print set(list_a).difference(set(list_b))
答案是set([1])
可以打印为列表,
print list(set(list_a).difference(set(list_b)))
解决方案 9:
由于目前的解决方案均未产生元组,因此我将加入以下内容:
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))
与此方向的其他非元组结果答案一样,它保留了顺序
解决方案 10:
如果您真正关注性能,那么请使用numpy!
这是 github 上的完整笔记本,其中比较了 list、numpy 和 pandas。
https://gist.github.com/denfromufa/2821ff59b02e9482be15d27f2bbd4451
解决方案 11:
我想要一个可以接受两个列表并能执行diff
inbash
所做的事情的东西。由于这个问题在您搜索“python diff two lists”时首先出现,并且不是很具体,所以我将发布我想到的内容。
使用SequenceMather
fromdifflib
可以像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']
当然,如果您的应用程序做出的假设与其他答案相同,那么您将从中受益最多。但如果您正在寻找真正的diff
功能,那么这是唯一的方法。
例如,其他答案都无法处理:
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]
解决方案 12:
这是Counter
针对最简单情况的答案。
这比上面进行双向差异的程序要短,因为它只执行问题所要求的操作:生成第一个列表中的内容但不包含第二个列表的内容的列表。
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']
解决方案 13:
这甚至可能比马克的列表理解还要快:
list(itertools.filterfalse(set(temp2).__contains__, temp1))
解决方案 14:
这是@SuperNova答案的修改版本
def get_diff(a: list, b: list) -> list:
return list(set(a) ^ set(b))
解决方案 15:
arulmr解决方案的单行版本
def diff(listA, listB):
return set(listA) - set(listB) | set(listB) -set(listA)
解决方案 16:
这是另一种解决方案:
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
解决方案 17:
假设我们有两个列表
list1 = [1, 3, 5, 7, 9]
list2 = [1, 2, 3, 4, 5]
从以上两个列表中我们可以看出,项目 1、3、5 存在于列表 2 中,而项目 7、9 不存在。另一方面,项目 1、3、5 存在于列表 1 中,而项目 2、4 不存在。
返回包含项目 7、9 和 2、4 的新列表的最佳解决方案是什么?
以上所有答案都找到了解决方案,那么最优解决方案是什么?
def difference(list1, list2):
new_list = []
for i in list1:
if i not in list2:
new_list.append(i)
for j in list2:
if j not in list1:
new_list.append(j)
return new_list
相对
def sym_diff(list1, list2):
return list(set(list1).symmetric_difference(set(list2)))
使用 timeit 我们可以看到结果
t1 = timeit.Timer("difference(list1, list2)", "from __main__ import difference,
list1, list2")
t2 = timeit.Timer("sym_diff(list1, list2)", "from __main__ import sym_diff,
list1, list2")
print('Using two for loops', t1.timeit(number=100000), 'Milliseconds')
print('Using two for loops', t2.timeit(number=100000), 'Milliseconds')
返回
[7, 9, 2, 4]
Using two for loops 0.11572412995155901 Milliseconds
Using symmetric_difference 0.11285737506113946 Milliseconds
Process finished with exit code 0
解决方案 18:
如果您要从列表a中删除列表b中存在的所有值。
def list_diff(a, b):
r = []
for i in a:
if i not in b:
r.append(i)
return r
列表差异([1,2,2],[1])
结果:[2,2]
或者
def list_diff(a, b):
return [x for x in a if x not in b]
解决方案 19:
如果差异列表的元素已排序并设置,则可以使用一种简单的方法。
list1=[1,2,3,4,5]
list2=[1,2,3]
print list1[len(list2):]
或使用本机设置方法:
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
解决方案 20:
如果你遇到TypeError: unhashable type: 'list'
需要将列表或集合转换为元组的情况,例如
set(map(tuple, list_of_lists1)).symmetric_difference(set(map(tuple, list_of_lists2)))
另请参阅如何比较 python 中的列表/集合列表?
解决方案 21:
我参与这个游戏有点晚了,但你可以将上面提到的一些代码与这个进行比较,其中最快的两个竞争者是,
list(set(x).symmetric_difference(set(y)))
list(set(x) ^ set(y))
对于初级的编码水平,我深感抱歉。
import time
import random
from itertools import filterfalse
# 1 - performance (time taken)
# 2 - correctness (answer - 1,4,5,6)
# set performance
performance = 1
numberoftests = 7
def answer(x,y,z):
if z == 0:
start = time.clock()
lists = (str(list(set(x)-set(y))+list(set(y)-set(y))))
times = ("1 = " + str(time.clock() - start))
return (lists,times)
elif z == 1:
start = time.clock()
lists = (str(list(set(x).symmetric_difference(set(y)))))
times = ("2 = " + str(time.clock() - start))
return (lists,times)
elif z == 2:
start = time.clock()
lists = (str(list(set(x) ^ set(y))))
times = ("3 = " + str(time.clock() - start))
return (lists,times)
elif z == 3:
start = time.clock()
lists = (filterfalse(set(y).__contains__, x))
times = ("4 = " + str(time.clock() - start))
return (lists,times)
elif z == 4:
start = time.clock()
lists = (tuple(set(x) - set(y)))
times = ("5 = " + str(time.clock() - start))
return (lists,times)
elif z == 5:
start = time.clock()
lists = ([tt for tt in x if tt not in y])
times = ("6 = " + str(time.clock() - start))
return (lists,times)
else:
start = time.clock()
Xarray = [iDa for iDa in x if iDa not in y]
Yarray = [iDb for iDb in y if iDb not in x]
lists = (str(Xarray + Yarray))
times = ("7 = " + str(time.clock() - start))
return (lists,times)
n = numberoftests
if performance == 2:
a = [1,2,3,4,5]
b = [3,2,6]
for c in range(0,n):
d = answer(a,b,c)
print(d[0])
elif performance == 1:
for tests in range(0,10):
print("Test Number" + str(tests + 1))
a = random.sample(range(1, 900000), 9999)
b = random.sample(range(1, 900000), 9999)
for c in range(0,n):
#if c not in (1,4,5,6):
d = answer(a,b,c)
print(d[1])
解决方案 22:
这里有一些简单的、保序的方法来区分两个字符串列表。
代码
一种不寻常的方法,使用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']
假设两个列表都包含具有相同开头的字符串。有关更多详细信息,请参阅文档。请注意,与集合操作相比,它并不是特别快。
直接使用以下方法实现itertools.zip_longest
:
import itertools as it
[x for x, y in it.zip_longest(temp1, temp2) if x != y]
# ['Three', 'Four']
解决方案 23:
我更喜欢先转换为集合,然后使用“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']
这是最容易理解的,而且将来如果你处理大量数据,如果不需要重复项,将其转换为集合将删除重复项。希望有帮助 ;-)
解决方案 24:
我知道这个问题已经有了很好的答案,但我希望添加以下方法numpy
。
temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two']
list(np.setdiff1d(temp1,temp2))
['Four', 'Three'] #Output
解决方案 25:
如果你想要更像变更集的东西......可以使用 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"
解决方案 26:
我们可以计算列表的交集减并集:
temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two', 'Five']
set(temp1+temp2)-(set(temp1)&set(temp2))
Out: set(['Four', 'Five', 'Three'])
解决方案 27:
这可以用一行代码解决。问题是给定两个列表(temp1 和 temp2),在第三个列表(temp3)中返回它们的差值。
temp3 = list(set(temp1).difference(set(temp2)))
解决方案 28:
这是一个区分两个列表(无论内容是什么)的简单方法,您可以得到如下所示的结果:
>>> 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])
希望这会有所帮助。
解决方案 29:
您可以循环浏览第一个列表,并将第二个列表中不存在但第一个列表中存在的每个项目添加到第三个列表中。例如:
temp3 = []
for i in temp1:
if i not in temp2:
temp3.append(i)
print(temp3)
解决方案 30:
在所有可能的选项中,最快的选项是:
s = set(temp2);
[x for x in temp1 if x not in s]
性能结果
import timeit
init = 'temp1 = list(range(100)); temp2 = [i * 2 for i in range(50)]'
print(timeit.timeit('list(set(temp1) - set(temp2))', init, number = 100000))
print(timeit.timeit('s = set(temp2);[x for x in temp1 if x not in s]', init, number = 100000))
print(timeit.timeit('[item for item in temp1 if item not in temp2]', init, number = 100000))
print(timeit.timeit('list(set(temp1) ^ set(temp2))', init, number = 100000))
运行代码片段Hide results展开片段
结果
0.3485999000258744
0.3314229999668896
2.067719299986493
0.3791518000070937