Possible Duplicate:
Sorting or Finding Max Value by the second element in a nested list. Python可能的重复:通过嵌套列表中的第二个元素排序或查找最大值。Python
I have a list with ~10^6 tuples in it like this:
我有一个列表,这样~ 10 ^ 6元组:
[(101, 153), (255, 827), (361, 961), ...]
^ ^
X Y
I want to find the maximum value of the Ys in this list, but also want to know the X that it is bound to.
我想在这个列表中找到y的最大值,但同时也想知道它所绑定的X。
How do I do this?
我该怎么做呢?
3 个解决方案
#1
99
Use max()
:
使用max():
Using itemgetter()
:
使用itemgetter():
In [53]: lis=[(101, 153), (255, 827), (361, 961)]
In [81]: from operator import itemgetter
In [82]: max(lis,key=itemgetter(1))[0] #faster solution
Out[82]: 361
using lambda
:
使用λ:
In [54]: max(lis,key=lambda item:item[1])
Out[54]: (361, 961)
In [55]: max(lis,key=lambda item:item[1])[0]
Out[55]: 361
timeit
comparison:
时间比较:
In [30]: %timeit max(lis,key=itemgetter(1))
1000 loops, best of 3: 232 us per loop
In [31]: %timeit max(lis,key=lambda item:item[1])
1000 loops, best of 3: 556 us per loop
#2
4
In addition to max, you can also sort:
除了max,你还可以排序:
>>> lis
[(101, 153), (255, 827), (361, 961)]
>>> sorted(lis,key=lambda x: x[1], reverse=True)[0]
(361, 961)
#3
0
You could loop through the list and keep the tuple in a variable and then you can see both values from the same variable...
您可以循环遍历列表并将tuple保存在一个变量中,然后您可以从同一个变量中看到两个值……
num=(0, 0)
for item in tuplelist:
if item[1]>num[1]:
num=item #num has the whole tuple with the highest y value and its x value
#1
99
Use max()
:
使用max():
Using itemgetter()
:
使用itemgetter():
In [53]: lis=[(101, 153), (255, 827), (361, 961)]
In [81]: from operator import itemgetter
In [82]: max(lis,key=itemgetter(1))[0] #faster solution
Out[82]: 361
using lambda
:
使用λ:
In [54]: max(lis,key=lambda item:item[1])
Out[54]: (361, 961)
In [55]: max(lis,key=lambda item:item[1])[0]
Out[55]: 361
timeit
comparison:
时间比较:
In [30]: %timeit max(lis,key=itemgetter(1))
1000 loops, best of 3: 232 us per loop
In [31]: %timeit max(lis,key=lambda item:item[1])
1000 loops, best of 3: 556 us per loop
#2
4
In addition to max, you can also sort:
除了max,你还可以排序:
>>> lis
[(101, 153), (255, 827), (361, 961)]
>>> sorted(lis,key=lambda x: x[1], reverse=True)[0]
(361, 961)
#3
0
You could loop through the list and keep the tuple in a variable and then you can see both values from the same variable...
您可以循环遍历列表并将tuple保存在一个变量中,然后您可以从同一个变量中看到两个值……
num=(0, 0)
for item in tuplelist:
if item[1]>num[1]:
num=item #num has the whole tuple with the highest y value and its x value