考虑一个字典,其中键是整数,值也是具有两个键的字典,如下所示:
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]}]
有没有一种方法可以使用列表或字典理解来获得连续的编号?你知道吗
有一种方法是使用字典理解,并使用^{} 根据字段
features
对tasks
中的项进行分组:与
tasknew
类似:相关问题 更多 >
编程相关推荐