Python列表的列表,获取最大值索引 [英] Python list of dicts, get max value index
问题描述
我正在尝试在字典列表中找到最大'size'
的字典索引:
ld = [{'prop':'foo','size':100},{'prop':'boo','size':200} ]
与以下代码我可以采取最大的大小:
items = [x ['size'] for x in ld]
/ pre>
print max(items)
我现在可以如何使用其索引?有没有一个简单的方法?
测试:
这样做:
items = [x ['size'] for x in ld]
max_val = max )
print items.index(max_val)
是否正确?
解决方案告诉
max()
如何计算索引序列的最大值: p>
max(xrange(len(ld)),key = lambda index:ld [index] ['size'])
这将返回
大小
键的索引是最高的:>>> ld = [{'prop':'foo','size':100},{'prop':'boo','size':200}]
>>> max(xrange(len(ld)),key = lambda index:ld [index] ['size'])
1
>>> ld [1]
{'size':200,'prop':'boo'}
如果你一直想要这本字典,那么你可以使用:
max(ld,key = lambda d:d ['size'])
并获得索引和字典,您可以使用
enumerate()
这里:max(枚举(ld),key = lambda item:item [1] ['size'])
演示:
>>> max(ld,key = lambda d:d ['size'])
{'size':200,'prop':'boo'}
>>> max(enumerate(ld),key = lambda item:item [1] ['size'])
(1,{'size':200,'prop':'boo'})
键
函数依次传递输入序列中的每个元素,而max()
将选择该键的返回值
函数最高的元素。
使用单独的列表来提取所有
大小
值,然后将其映射回原始列表不是很有效(您现在需要重复列表两次)。list.index()
无法正常工作,因为它必须匹配整个字典,而不仅仅是一个值。I'm trying to get the index of the dictionary with the max
'size'
in a list of dictionaries like the following:ld = [{'prop': 'foo', 'size': 100}, {'prop': 'boo', 'size': 200}]
with the following code I can take the maximum size:
items = [x['size'] for x in ld] print max(items)
How can I take its index now? Is there an easy way?
Test:
I just figured i can do that:
items = [x['size'] for x in ld] max_val = max(items) print items.index(max_val)
is it correct?
解决方案Tell
max()
how to calculate the maximum for a sequence of indices:max(xrange(len(ld)), key=lambda index: ld[index]['size'])
This'll return the index for which the
size
key is the highest:>>> ld = [{'prop': 'foo', 'size': 100}, {'prop': 'boo', 'size': 200}] >>> max(xrange(len(ld)), key=lambda index: ld[index]['size']) 1 >>> ld[1] {'size': 200, 'prop': 'boo'}
If you wanted that dictionary all along, then you could just use:
max(ld, key=lambda d: d['size'])
and to get both the index and the dictionary, you could use
enumerate()
here:max(enumerate(ld), key=lambda item: item[1]['size'])
Some more demoing:
>>> max(ld, key=lambda d: d['size']) {'size': 200, 'prop': 'boo'} >>> max(enumerate(ld), key=lambda item: item[1]['size']) (1, {'size': 200, 'prop': 'boo'})
The
key
function is passed each element in the input sequence in turn, andmax()
will pick the element where the return value of thatkey
function is highest.Using a separate list to extract all the
size
values then mapping that back to your original list is not very efficient (you now need to iterate over the list twice).list.index()
cannot work as it has to match the whole dictionary, not just one value in it.这篇关于Python列表的列表,获取最大值索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!