在列表中分组元组

2024-05-14 16:21:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个列表中有一组元组,在其中我试图将相似的项组合在一起。 例如

[('/Desktop/material_design_segment/arc_01.texture', 'freshnel_intensity_3.0022.jpg'),
 ('/Desktop/material_design_segment/arc_01.texture', 'freshnel_intensity_4.0009.jpg'),
 ('/Desktop/material_design_segment/arc_08.texture', 'freshnel_intensity_8.0020.jpg'),
 ('/Desktop/material_design_segment/arc_05.texture', 'freshnel_intensity_5.0009.jpg'),
 ('/Desktop/material_design_filters/custom/phase_03.texture', 'rounded_viscosity.0002.jpg'),
 ('/Desktop/material_design_filters/custom/phase_03.texture', 'freshnel_intensity_9.0019.jpg')]

我的结果应该会返回给我:

'/Desktop/material_design_segment/arc_01.texture':
    'freshnel_intensity_3.0022.jpg',
    'freshnel_intensity_4.0009.jpg',
'/Desktop/material_design_segment/arc_08.texture':
    'freshnel_intensity_8.0020.jpg'
'/Desktop/material_design_segment/arc_05.texture':
    'freshnel_intensity_5.0009.jpg'
'/Desktop/material_design_filters/custom/phase_03.texture':
    'rounded_viscosity.0002.jpg',
    'freshnel_intensity_9.0019.jpg'

但是,当我尝试使用下面的代码时,它只返回1项

groups = defaultdict(str)
for date, value in aaa:
    groups[date] = value

pprint(groups)

这是输出:

{'/Desktop/material_design_segment/arc_01.texture': 'freshnel_intensity_4.0009.jpg'
 '/Desktop/material_design_filters/custom/phase_03.texture': 'freshnel_intensity_9.0019.jpg'
 '/Desktop/material_design_segment/arc_08.texture': 'freshnel_intensity_8.0020.jpg'
 '/Desktop/material_design_segment/arc_05.texture': 'freshnel_intensity_5.0009.jpg'}

我哪里做错了


Tags: datecustomsegmentfiltersgroupsjpgmaterialdesign
2条回答

您应该将这些值附加到一个列表中,如下所示(基于您的代码):

groups = defaultdict(list)
for date, value in aaa:
    groups[date].append(value)

print(groups)

您正在将value赋值给groups[date],这将覆盖上一个值。你需要把它附加到一个列表中

groups = defaultdict(list)
for date, value in aaa:
    groups[date].append(value)

相关问题 更多 >

    热门问题