Tell max()
how to calculate the maximum for a sequence of indices:
max(range(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(range(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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…