我在列表中有一组元组,我试图将类似的项目组合在一起。 例如
[('/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'}
我在哪里做错了?
答案 0 :(得分:1)
您将value
分配给groups[date]
,这会覆盖之前的值。您需要将其附加到列表中。
groups = defaultdict(list) for date, value in aaa: groups[date].append(value)
答案 1 :(得分:0)
您应该按如下方式将值附加到列表中(基于您的代码):
groups = defaultdict(list)
for date, value in aaa:
groups[date].append(value)
print(groups)