[英]Most Pythonic Way to Select Particular Tuple from List of Tuples
Suppose I have a list of tuples: pairs = [(4,5),(2,6),(6,9),(8,7),(1,1)]
. 假设我有一个元组列表: 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
. 我有一个函数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. 我试图找到m
返回最大输出的pairs
元素。 Specifically, I want to do this as pythonically as possible. 具体来说,我想尽可能地用Python做到这一点。
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. 对我来说很明显,我可以通过pairs
循环和一个变量来执行此操作,以存储看到的最大收益货币对,但这感觉并不雅致。 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. 也很明显,我可以通过声明temp = [m(p) for p in pairs]
然后选择pairs[temp.index(max(temp))]
来找到想要的pairs[temp.index(max(temp))]
,但我不想创建只要是成对的清单,另一个清单-同样,这感觉不佳。
Looking for pythonic suggestions. 寻找pythonic建议。
最Python化的方法:
result = max(pairs, key=m)
Couldn't you do 你不能吗
max([m(p) for p in pairs]) max([成对的p的m(p)])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.