Suppose I have a list of tuples: pairs = [(4,5),(2,6),(6,9),(8,7),(1,1)]
.
And I have a function def m(pair): return pair[0]**2 + pair[1]**2
.
I seek to find the element of pairs
for which m
returns the greatest output. Specifically, I want to do this as pythonically as possible.
It is clear to me that I could do this with a loop through pairs
and a variable to store the maximum-yielding pair seen, but that feels inelegant. I feel as if this should be done with a list comprehension. It is also clear that I could find the pair I want by declaring temp = [m(p) for p in pairs]
and then selecting pairs[temp.index(max(temp))]
, but I'd prefer not to create another list as long as the list of pairs -- again, this feels inelegant.
Looking for pythonic suggestions.
最Python化的方法:
result = max(pairs, key=m)
Couldn't you do
max([m(p) for p in pairs])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.