gpt4 book ai didi

python - 将元组分组到列表中

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

在 Python 中,使用公共(public)索引对元组进行分组的最佳方法是什么?

(2, 3, 'z')
(1, 1, 'abc')
(2, 1, 'stu')
(1, 2, 'def')
(2, 2, 'vxy')

结果将是:

[((1, 1, 'abc'),(1, 2, 'def')]
[((2, 1, 'stu'),(2, 2, 'vxy'), (2, 2, 'vxy')]

目标是将第三个元素连接成单个字符串对象。

这是连接部分,但我不确定分组。

def sort_tuples(list_input):
new = sorted(list_input)
str = ''
for i in range(0, len(new)):
str = str + new[i][2]
return str

最佳答案

使用字典进行分组;选择您的分组元素并将您想要连接的内容附加到每个键的列表中:

groups = {}
for first, second, third in list_input:
groups.setdefault(first, []).append(third)

然后您可以连接每个列表:

for key, group in groups.items():
print(key, ''.join(group))

由于您只想连接每个元组的第三个元素,因此我没有费心在字典中包含第二个元素,但您也可以自由地将整个元组存储在组列表中。

演示:

>>> list_input = [
... (2, 3, 'z'),
... (1, 1, 'abc'),
... (2, 1, 'stu'),
... (1, 2, 'def'),
... (2, 2, 'vxy'),
... ]
>>> groups = {}
>>> for first, second, third in list_input:
... groups.setdefault(first, []).append(third)
...
>>> for key, group in groups.items():
... print(key, ''.join(group))
...
1 abcdef
2 zstuvxy

如果第二个键被用作排序键,那么您必须在分组时包含它;然后您可以排序并提取第三个:

groups = {}
for first, second, third in list_input:
groups.setdefault(first, []).append((second, third))

for key, group in groups.items():
print(key, ''.join([third for second, third in sorted(group)]))

演示:

>>> groups = {}
>>> for first, second, third in list_input:
... groups.setdefault(first, []).append((second, third))
...
>>> for key, group in groups.items():
... print(key, ''.join([third for second, third in sorted(group)]))
...
1 abcdef
2 stuvxyz

由于这涉及到排序,所以不妨对整个输入列表进行一次排序,并使用 itertools.groupby()排序后对输入进行分组:

from itertools import groupby

for key, group in groupby(sorted(list_input), key=lambda t: t[0]):
print(key, ''.join([third for first, second, third in group]))

再次演示一下这种方法:

>>> from itertools import groupby
>>> for key, group in groupby(sorted(list_input), key=lambda t: t[0]):
... print(key, ''.join([third for first, second, third in group]))
...
1 abcdef
2 stuvxyz

字典分组方法是 O(N) 算法),一旦添加排序,它就变成 O(NlogN) 算法。

关于python - 将元组分组到列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28128306/

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