gpt4 book ai didi

python - 如何在从python中的动态输入中删除重复项的同时合并两个列表

转载 作者:行者123 更新时间:2023-12-04 16:36:33 26 4
gpt4 key购买 nike

我有一个这样的列表:

[{'groups': ['Engineer', 'It', 'Office Floor 2', 'Penang']}, {'groups': ['Engineer', 'Penang', 'Testnew' ]}]

我想做的就是将它分开以删除列表中的重复项,例如:

['Engineer', 'It', 'Office Floor 2', 'Penang', 'Testnew']

我试过这段代码:

list_1 = ['Engineer', 'It', 'Office Floor 2', 'Penang']
list_2 = ['Engineer', 'Penang', 'Testnew']

set_1 = set(list_1)
set_2 = set(list_2)

list_2_items_not_in_list_1 = list(set_2 - set_1)
combined_list = list_1 + list_2_items_not_in_list_1

print(combined_list)

虽然它有效,但如何将其修改为动态列表?由于我的列表不是静态的,它可能会根据用户输入的数量而变化。

最佳答案

如果出现的顺序是一个约束,你可以这样做:

lst = [{'groups': ['Engineer', 'It', 'Office Floor 2', 'Penang']}, {'groups': ['Engineer', 'Penang', 'Testnew']}]

seen = set()
result = []
for d in lst:
for e in d["groups"]:
if e not in seen:
result.append(e)
seen.add(e)
print(result)

输出

['Engineer', 'It', 'Office Floor 2', 'Penang', 'Testnew']

如果出现顺序不受限制:

from itertools import chain
result = list(set(chain.from_iterable(d["groups"] for d in lst)))
print(result)

输出

['Office Floor 2', 'Penang', 'Testnew', 'It', 'Engineer']

或者简单地说:

result = list(set(e for d in lst for e in d["groups"]))

关于python - 如何在从python中的动态输入中删除重复项的同时合并两个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69284109/

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