gpt4 book ai didi

python - 根据迭代的内部列表值合并两个外部列表

转载 作者:行者123 更新时间:2023-12-01 06:07:14 25 4
gpt4 key购买 nike

我有两个列表列表 - 即

[['1', 'expired', 'test', '0'], ['31', 'active', 'test', '1']]

以及

[['1', 'Andrew', 'Alexander'], ['31', 'John', 'Smith']]

我们称它们为list1list2

我想合并 list1list2,但仅当(注意,这是伪代码,试图弄清楚如何在 Python 中对其进行编程)

x[0] in list1 == x[0] in list2

我不知道如何写出来。

我所说的合并是指(伪代码)

list[x] = list1[x] + list2[x] while x[0] in list1 == x[0] in list2

所需输出:

[['1', 'expired', 'test', '0', '1', 'Andrew', 'Alexander'], ['31', 'active', 'test', '1', '31', 'John', 'Smith']]

唯一的关键点是并非所有 x[0] 都会完美匹配。

最佳答案

利用agf的想法,采用collections.defaultdict ,这在 O(m+n) 中,其中 mn 是列表的长度。

import collections
import itertools

x=[['1', 'expired', 'test', '0'], ['31', 'active', 'test', '1']]
y=[['1', 'Andrew', 'Alexander'], ['31', 'John', 'Smith']]

result=collections.defaultdict(list)
for item in itertools.chain(x,y):
result[item[0]].append(item)
result=[list(itertools.chain.from_iterable(value)) for value in result.values()]
print(result)

产量

[['1', 'expired', 'test', '0', '1', 'Andrew', 'Alexander'], ['31', 'active', 'test', '1', '31', 'John', 'Smith']]
<小时/>

在评论中OP说期望的输出是

[['1', 'expired', 'test', '0', 'Andrew', 'Alexander'], ['31', 'active', 'test', '1', 'John', 'Smith']]

(这与原始问题中发布的所需输出不同。)

然后:

import collections
import itertools

x=[['1', 'expired', 'test', '0'], ['31', 'active', 'test', '1']]
y=[['1', 'Andrew', 'Alexander'], ['31', 'John', 'Smith']]

result={}
for item in itertools.chain(x,y):
result.setdefault(item[0],item[:1]).extend(item[1:])
result=result.values()
print(result)

这是我发现使用 setdefault 的少数几次之一比collections.defaultdict更方便。

关于python - 根据迭代的内部列表值合并两个外部列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7477167/

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