gpt4 book ai didi

python - 列表差异

转载 作者:太空宇宙 更新时间:2023-11-03 14:13:18 25 4
gpt4 key购买 nike

我想编写一个函数来给出列表之间的差异。例如,

list1 = ['a','a','a','b','c','d','d']
list2 = ['a','a','a','b','c','a','d']
list = diff(list1, list2)
print(list)

列表应该是['d','a'],两者都不匹配的元素。我想过使用 set 但它不起作用,因为它会消除重复字符。

最佳答案

两个列表的长度相同,您可以使用zip:

res = []
for x, y in zip(list1, list2):
if x != y:
res.extend((x, y))
print(res)

输出:

['d', 'a']

或者单行:

>>> [z for x, y in zip(list1, list2) if x != y for z in (x, y)]
['d', 'a']

如果两个列表的长度不同,并且您希望将其算作差异,则可以使用 zip_longest:

from itertools import zip_longest

list1 = ['a','a','a','b','c','d','d', 'x']
list2 = ['a','a','a','b','c','a','d']

res = []

for x, y in zip_longest(list1, list2):
if x != y:
res.extend((x, y))
print(res)

输出:

['d', 'a', 'x', None]

再次作为一句台词

>>> [z for x, y in zip_longest(list1, list2) if x != y for z in (x, y)]
['d', 'a', 'x', None]

关于python - 列表差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48354887/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com