我有我想要的值添加到特定列表列表的字典的字典...追加元素到最小列表中列出
d = {'a': [4, 2], 'b': [3, 4], 'c': [4, 3], 'd': [4, 3], 'e': [4], 'f': [4], 'g': [4]}
我想2號添加到剛其中一個長度最小的列表。
def gsl(x):
return [k for k in x.keys() if len(x.get(k))==min([len(n) for n in x.values()])]
調用
>>> gsl(d)
['e', 'g', 'f']
因此,在這種情況下後,我想2號添加到列表'e'
在字典使其[4,2]
(順序並不重要。
結果應該是我想試試
for i in d:
if gsl(d)[0] == i: #gets the first key with the smallest value
d[i].append(2) # if equal, adds 2 to the dictionary value that matches
除了增加2
每個'e'
,'g'
,'f'
。
在此先感謝!
嘗試殺死for循環,看看是否有幫助 – inspectorG4dget 2012-07-31 00:32:29