如何从包含重复值的列表中制作字典

2024-10-06 12:46:02 发布

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

我是python新手,在尝试将下面的列表转换成字典的过程中,我已经奋斗了一段时间。你知道吗

lst = ['AB_MK1230', 'MK12303', 86.17, 'AB_MK1230', 'MK12302', 89.99, 
'AB_MK1230', 'MK12301', 93.82, 'AB_MK1230', 'MK12301', 94.81, 'AB_MK1230', 
'MK12303', 87.5, 'AB_MK1230', 'MK12302', 94.67, 'AB_MK1230', 'MK12302', 90.32, 
'AB_MK1230',  'MK12303', 89.26, 'AB_MK1230',  'MK12301', 91.75,'AB_MK1230', 
'MK12302', 88.54, 'AB_MK1230', 'MK12303', 92.5,'AB_MK1230', 'MK12301', 93.49, 
'AB_MK1230', 'MK12301', 86.47,'AB_MK1230', 'MK12302', 84.79,'AB_MK1230', 
'MK12303', 86.57,'AB_MK1230', 'MK12301', 79.24,'AB_MK1230', 'MK12302', 80.34, 
'AB_MK1230', 'MK12303', 76.88] 

abu MK1230是父扇区,MK12303、MK12301和MK12302是子扇区。我的输出是拥有一个字典,其中包含每个子扇区和父扇区的键,并将float值作为该键的值,如下所示。你知道吗

dict = {MK12301: AB_MK1230, 93.82, 94.81, 91.75, 93.49, 86.47, 79.24
        MK12302: AB_MK1230, 89.99, 94.67, 90.32, 88.54, 84.79, 80.34
        MK12303: AB_MK1230, 86.17, 87.50, 89.26, 92.50, 86.57, 76.88 }

我已经阅读了一些来自https://docs.python.org/3/tutorial/datastructures.html?highlight=dictionaries的文档,但是我仍然无法找到解决方案。你知道吗

我怎样才能做到这一点?你知道吗


Tags: https列表字典ab过程floatdict扇区
1条回答
网友
1楼 · 发布于 2024-10-06 12:46:02

我们遍历这个列表,一次按(parent, child, value)顺序解包三个项目。使用(parent, child)作为字典的键,然后将值添加到set。你知道吗

import itertools
import collections

lst = ['AB_MK1230', 'MK12303', 86.17, 'AB_MK1230', 'MK12302', 89.99, 
'AB_MK1230', 'MK12301', 93.82, 'AB_MK1230', 'MK12301', 94.81, 'AB_MK1230', 
'MK12303', 87.5, 'AB_MK1230', 'MK12302', 94.67, 'AB_MK1230', 'MK12302', 90.32, 
'AB_MK1230',  'MK12303', 89.26, 'AB_MK1230',  'MK12301', 91.75,'AB_MK1230', 
'MK12302', 88.54, 'AB_MK1230', 'MK12303', 92.5,'AB_MK1230', 'MK12301', 93.49, 
'AB_MK1230', 'MK12301', 86.47,'AB_MK1230', 'MK12302', 84.79,'AB_MK1230', 
'MK12303', 86.57,'AB_MK1230', 'MK12301', 79.24,'AB_MK1230', 'MK12302', 80.34, 
'AB_MK1230', 'MK12303', 76.88]

d = collections.defaultdict(set)
for parent, child, value in itertools.zip_longest(*[iter(lst)]*3, fillvalue=None):
    d[(parent, child)].add(value)

d现在是一本类似于字典的书

defaultdict(set,
            {('AB_MK1230', 'MK12301'): {79.24,
              86.47,
              91.75,
              93.49,
              93.82,
              94.81},
             ('AB_MK1230', 'MK12302'): {80.34,
              84.79,
              88.54,
              89.99,
              90.32,
              94.67},
             ('AB_MK1230', 'MK12303'): {76.88,
              86.17,
              86.57,
              87.5,
              89.26,
              92.5}})

还不完全清楚最终的数据结构应该是什么样子。如果您只希望parent作为顶级键,那么可以使用嵌套的defaultdict。。。你知道吗

相关问题 更多 >