gpt4 book ai didi

python - 根据元素名称在python中对长列表的元素进行分组

转载 作者:太空宇宙 更新时间:2023-11-04 09:34:50 25 4
gpt4 key购买 nike

我有一个长长的列表,如下所示,我分别根据(元素[0]、元素[3]、元素[2])对它们进行了排序。对于元素,我的意思是下划线之间的数字。

list3=['20180406_145813_4_1.jpg',
'20180406_145813_5_1.jpg',
'20180406_145813_6_1.jpg',
'20180406_175827_10_12.jpg',
'20180406_175827_11_12.jpg',
'20180409_190651_7_2.jpg',
'20180409_190651_8_2.jpg',
...]

现在,我想根据元素[3]拆分列表。我想要的结果是:

[['20180406_145813_4_1.jpg',
'20180406_145813_5_1.jpg',
'20180406_145813_6_1.jpg'],
['20180406_175827_10_12.jpg',
'20180406_175827_11_12.jpg'],
['20180409_190651_7_2.jpg',
'20180409_190651_8_2.jpg'],
...]

我有这段代码可以将每个名字打印成一个列表。我不知道如何在这段代码中按 element3 分组:

for imagename in list3:
element3 = imagename.split("_")[3]
for j,m in groupby(list3):
print(list(m))

最佳答案

您可以使用 itertools.groupby像这样:

from itertools import groupby

list3 = ['20180406_145813_4_1.jpg',
'20180406_145813_5_1.jpg',
'20180406_145813_6_1.jpg',
'20180406_175827_10_12.jpg',
'20180406_175827_11_12.jpg',
'20180409_190651_7_2.jpg',
'20180409_190651_8_2.jpg']

result = [list(group) for _, group in groupby(list3, key=lambda x: x.split('_')[3])]
print(result)

输出

[['20180406_145813_4_1.jpg', '20180406_145813_5_1.jpg', '20180406_145813_6_1.jpg'], ['20180406_175827_10_12.jpg', '20180406_175827_11_12.jpg'], ['20180409_190651_7_2.jpg', '20180409_190651_8_2.jpg']]

以上list comprehension等同于以下 for 循环:

result = []
for _, group in groupby(list3, key=lambda x: x.split('_')[3]):
result.append(list(group))

关于python - 根据元素名称在python中对长列表的元素进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54169651/

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