gpt4 book ai didi

python - 在列表和字典的组合中对值进行分组

转载 作者:行者123 更新时间:2023-11-28 22:11:13 29 4
gpt4 key购买 nike

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

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)

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

有没有办法使用列表或字典理解来获取连续编号?

最佳答案

这是使用字典推导式执行此操作的一种方法,并根据字段 features 使用 itertools.groupbytasks 中的项目进行分组。 :

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

关于python - 在列表和字典的组合中对值进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56003825/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com