gpt4 book ai didi

python - 将列表中的数据分组

转载 作者:行者123 更新时间:2023-12-03 19:03:56 25 4
gpt4 key购买 nike

我现在正在学习 python,我正在尝试从列表中对数据进行分组

raw_list = [
['item3', [10, 10, 1]],
['item4', [10, 10, 2]],
['item7', [10, 10, 2]],
['item8', [10, 10, 2]],
['item2', [10, 10, 3]],
['item5', [10, 10, 4]],
['item1', [10, 10, 20]],
['item6', [10, 10, 20]],
['item9', [10, 10, 20]]
]
我正在尝试按嵌套列表中的第三个数字 (1,2,3,4,20) 分组:
group = [
[
['item3', [10, 10, 1]]
],
[
['item4', [10, 10, 2]],
['item7', [10, 10, 2]],
['item8', [10, 10, 2]]
],
[
['item2', [10, 10, 3]]
],
[
['item5', [10, 10, 4]]
],
[
['item1', [10, 10, 20]],
['item6', [10, 10, 20]],
['item9', [10, 10, 20]]
]
]
我的代码:
raw_list.sort(key=lambda x: x[1][2])

group_list = list(i for i in itertools.groupby(raw_list, lambda x: x[1][2]))
print(group_list)
我认为它几乎可以正常工作,但是我无法获取每个组的列表,因为它返回以下内容:
[(1, <itertools._grouper object at 0x019AB7D8>), (2, <itertools._grouper object at 0x019B8430>), (3, <itertools._grouper object at 0x019B8730>), (4, <itertools._grouper object at 0x039E1F10>), (20, <itertools._grouper object at 0x039E1F70>)]

最佳答案

你真的很亲近。 itertools.groupby产生形式为 (key, group) 的元组哪里group是一个迭代器。如果您转换每个 group 中的项目到一个列表,你会得到你想要的。

raw_list.sort(key=lambda x: x[1][2])

# Notice the change in the list comprehension
group_list = [list(g) for _, g in itertools.groupby(raw_list, lambda x: x[1][2])]

print(group_list)
输出以下列表(然后我对其进行了格式化)
[
[
['item3', [10, 10, 1]]
],
[
['item4', [10, 10, 2]],
['item7', [10, 10, 2]],
['item8', [10, 10, 2]]
],
[
['item2', [10, 10, 3]]
],
[
['item5', [10, 10, 4]]
],
[
['item1', [10, 10, 20]],
['item6', [10, 10, 20]],
['item9', [10, 10, 20]]
]
]

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

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