组合列表和字典中的值

时间:2019-05-06 10:59:51

标签: python list dictionary

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

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]

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

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)

tasknew [[[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]}]

是否可以使用列表或字典理解来获取连续编号?

1 个答案:

答案 0 :(得分:4)

这是使用字典理解来执行此操作的一种方法,并使用itertools.groupby根据字段tasksfeatures中的项目分组:

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]]]