简体   繁体   English

从元组列表中选择特定元组的大多数Python方法

[英]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.

相关问题 大多数pythonic方式转换元组列表 - Most pythonic way to convert a list of tuples 最Python化的方式来“或”元组? - Most pythonic way to 'or' tuples? 从元组列表创建元组的最有效方法 - Most efficient way of creating a tuple from list of tuples 如何使用Python以最pythonic的方式转换元组列表(可能使用zip) - How to transform a list of tuples with Python in the most pythonic way (perhaps with zip) 对列表中包含的每个元组进行索引的最 Pythonic 方法 - Most pythonic way to index each tuple contained within a list 将元组数字映射为“一个”以列出索引:大多数pythonic方式 - Mapping tuple numbers to list indexes as “ones”: most pythonic way 什么是将字典中元组的第二个 object 收集到列表中的最pythonic方式 - Whats most pythonic way of colelcting second object of tuple in dictionary into a list 在2元组序列中测试与第一项元组匹配的最Pythonic方法是什么? - What is the most Pythonic way to test for match with first item of tuple in sequence of 2-tuples? 大多数pythonic方法将这个元组用Python 2中的lambda解压缩到Python 3中 - Most pythonic way to port this tuple unpacking with lambda from Python 2 into Python 3 在列表中循环直到特定值的最pythonic方式是什么? - What is the most pythonic way of looping in a list until a particular value?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM