以列表和字典的组合对值进行分组

2024-05-17 06:58:53 发布

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

考虑一个字典,其中键是整数,值也是具有两个键的字典,如下所示:

servicesdict = { 0 : {'cost' : 30, 'features' : ['f1']},
    1 : {'cost' : 50, 'features' : ['f1']},
    2 : {'cost' : 70, 'features' : ['f1']},
    3 : {'cost' : 200, 'features' : ['f1']},
    4 : {'cost' : 20, 'features': ['f2']},

    5 : {'cost' : 10, 'features' : ['f3']},
    6 : {'cost' : 20, 'features' : ['f3']},
    7 : {'cost' : 50, 'features' : ['f3']},
    8 : {'cost' : 70, 'features' : ['f3']},
    9 : {'cost' : 20, 'features' : ['f4']},

    10 : {'cost' : 20, 'features': ['f5']},
    11 : {'cost' : 20, 'features': ['f5']},
    12 : {'cost' : 40, 'features': ['f5']},
    }

    t1 = [0,1,2,3,4]
    t2 = [5,6,7,8,9]
    t3 = [10,11,12]
    task = [ t1, t2, t3]

我们需要根据features的字典值对task中的子列表进行分组,并创建一个列表,其中每个子列表都用一个连续的值进行编号。我编写了以下代码,根据“功能”对这些值进行分组,这些功能可以正常工作并产生所需的输出:

tasknew = []
for t in task:
out = [[g for g in group] for key, group in itertools.groupby(t, key = lambda x:servicesdict[x]['features'])]
tasknew.append(out)


count = 0
newlist = []
for t in tasknew:
    x = dict()
    for c in t:
        x[count] = c
        count = count + 1
    newlist.append(x)

新任务[[[0, 1, 2, 3], [4]], [[5, 6, 7, 8], [9]], [[10, 11, 12]]]

新建列表 [{0: [0, 1, 2, 3], 1: [4]}, {2: [5, 6, 7, 8], 3: [9]}, {4: [10, 11, 12]}]

有没有一种方法可以使用列表或字典理解来获得连续的编号?你知道吗


Tags: in列表fortask字典countservicef5
1条回答
网友
1楼 · 发布于 2024-05-17 06:58:53

有一种方法是使用字典理解,并使用^{}根据字段featurestasks中的项进行分组:

from itertools import groupby, count
c = count()
newlist = [{next(c):list(v) for k,v in groupby(t, key= 
                             lambda x: servicesdict[x]['features'])} 
                             for t in task ]

print(new_list)

[{1: [0, 1, 2, 3], 2: [4]},
 {3: [5, 6, 7, 8], 4: [9]},
 {5: [10, 11, 12]}]

tasknew类似:

[[list(v) for k,v in groupby(t, key= 
          lambda x: servicesdict[x]['features'])] for t in task]
# [[[0, 1, 2, 3], [4]], [[5, 6, 7, 8], [9]], [[10, 11, 12]]]

相关问题 更多 >