[英]How do you find which key in a dictionary has the longest list of values?
I am attempting to figure out which Key in my dictionary has the longest list of values. 我试图找出字典中哪个键具有最长的值列表。 I am in a very simple Computer Science class so I cannot use lambda and other complex terms. 我上的是一门非常简单的计算机科学课,所以我不能使用lambda和其他复杂术语。 I'm wondering if there is a way to use loops, if statements, and len to do so? 我想知道是否有使用循环,if语句和len的方法?
Also how would I display the value of the key with the longest list of values? 另外,如何显示具有最长值列表的键的值?
A simple solution can go like this: 一个简单的解决方案可以像这样:
max_len = 0
max_key = ""
for key in d:
cur_len = len(d[key])
if cur_len>max_len:
max_key = key
max_len = cur_len
print max_key
x={'a':[9,8],'b':[1,2,3],'c':'1,2,3,4'}
print [k for k in x.keys() if x[k]==max(x.values(),key=len)]
You can try this. 你可以试试看
import itertools
preds = {'lion': ['gazelle', 'zebra', 'antelope'], 'eagle': ['sparrow', 'mouse'], 'crocodile': ['gazelle', 'antelope', 'buffalo', 'zebra']}
byprey = sorted([(len(v), k) for k, v in preds.iteritems()], reverse=True)
num, predator = byprey[0]
print predator
For python 3 you need only change iteritems
to items
eg 对于python 3,您只需iteritems
更改为items
例如
byprey = sorted([(len(v), k) for k, v in preds.items()], reverse=True)
and print is a function 打印是一种功能
print (predator)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.