簡體   English   中英

組合列表和字典中的值

[英]Grouping Values in a combination of List and 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]

我們需要根據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]]] 5,6,7,8 [[[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]}]

有沒有辦法使用列表或字典理解來獲得連續編號?

這是使用字典理解來執行此操作的一種方法,然后使用itertools.groupby根據字段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]]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM