python 列表求最大值_Python列表的列表,获取最大值索引

1586010002-jmsa.png

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值