将元素追加到列表字典中的最小列表 [英] Append element to smallest list in dictionary of lists
本文介绍了将元素追加到列表字典中的最小列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个列表字典,我想为其添加值到特定列表...
I have a dictionary of lists for which I want to add a value to a particular list...
d = {'a': [4, 2], 'b': [3, 4], 'c': [4, 3], 'd': [4, 3], 'e': [4], 'f': [4], 'g': [4]}
我想将2加到长度最小的列表中.
I want to add the number 2 to the just one of the lists with the smallest length.
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]
(顺序无关紧要.
So in this case, I want to append the number 2 to the list 'e'
in the dictionary making it [4,2]
(order doesnt matter.
结果应为
>>> d['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
除了在每个'e'
,'g'
,'f'
中添加 2
.
Except that adds 2
to each 'e'
, 'g'
, 'f'
.
提前谢谢!
推荐答案
>>> d = {'a': [4, 2], 'b': [3, 4], 'c': [4, 3], 'd': [4, 3], 'e': [4], 'f': [4], 'g': [4]}
>>> smallest = min(d, key=lambda k: len(d[k]))
>>> d[smallest].append(2)
>>> d
{'a': [4, 2], 'c': [4, 3], 'b': [3, 4], 'e': [4, 2], 'd': [4, 3], 'g': [4], 'f': [4]}
这篇关于将元素追加到列表字典中的最小列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文