且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python列表的列表,获取最大值索引

更新时间:2022-10-24 11:00:23

告诉 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, and max() will pick the element where the return value of that key 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.