Har*_*ime 50 python tuples min
我想找到按给定列排序的元组列表的最小值.我有一些数据被安排为例如2元组的列表.
data = [ (1, 7.57), (2, 2.1), (3, 1.2), (4, 2.1), (5, 0.01),
(6, 0.5), (7, 0.2), (8, 0.6)]
Run Code Online (Sandbox Code Playgroud)
如何通过比较元组中的第二个数字来找到数据集的最小值?
即
data[0][1] = 7.57
data[1][1] = 2.1
Run Code Online (Sandbox Code Playgroud)
min(数据)= (5, 0.01)
min( data )返回(1, 7.57),我接受的索引0的最小值是正确的,但我想要索引1的最小值.
Lev*_*sky 79
In [2]: min(data, key = lambda t: t[1])
Out[2]: (5, 0.01)
Run Code Online (Sandbox Code Playgroud)
要么:
In [3]: import operator
In [4]: min(data, key=operator.itemgetter(1))
Out[4]: (5, 0.01)
Run Code Online (Sandbox Code Playgroud)
使用 numpy,您可以使用这些命令来获取列表中 item 最小的元组:
使这项工作发挥作用的成分是 numpy 的高级数组切片和 argsort 功能。
import numpy as np
#create a python list of tuples and convert it to a numpy ndarray of floats
data = np.array([ (1, 7.57), (2, 2.1), (3, 1.2),
(4, 2.1), (5, 0.01), (6, 0.5), (7, 0.2), (8, 0.6)])
print("data is")
print(data)
#Generate sortIndices from second column
sortIndices = np.argsort(data[:,1])
print("sortIndices using index 1 is:" )
print(sortIndices)
print("The column at index 1 is:")
print(data[:,1])
print("Index 1 put into order using column 1")
print(data[sortIndices,1])
print("The tuples put into order using column 1")
print(data[sortIndices,:])
print("The tuple with minimum value at index 1")
print(data[sortIndices[0],:])
print("The tuple with maximum value at index 1")
print(data[sortIndices[-1],:])
Run Code Online (Sandbox Code Playgroud)
哪个打印:
data is
[[ 1. 7.57]
[ 2. 2.1 ]
[ 3. 1.2 ]
[ 4. 2.1 ]
[ 5. 0.01]
[ 6. 0.5 ]
[ 7. 0.2 ]
[ 8. 0.6 ]]
sortIndices using index 1 is:
[4 6 5 7 2 1 3 0]
The column at index 1 is:
[ 7.57 2.1 1.2 2.1 0.01 0.5 0.2 0.6 ]
Index 1 put into order using column 1
[ 0.01 0.2 0.5 0.6 1.2 2.1 2.1 7.57]
The tuples put into order using column 1
[[ 5. 0.01]
[ 7. 0.2 ]
[ 6. 0.5 ]
[ 8. 0.6 ]
[ 3. 1.2 ]
[ 2. 2.1 ]
[ 4. 2.1 ]
[ 1. 7.57]]
The tuple with minimum value at index 1
[ 5. 0.01]
The tuple with maximum value at index 1
[ 1. 7.57]
Run Code Online (Sandbox Code Playgroud)
即使 Lev 的答案是正确的,我也想添加 sort 方法,以防有人对第一个n 最小值感兴趣。需要考虑的一件事是min操作的运行时是O(N)排序所在的位置O(N Log N)
data = [ (1, 7.57), (2, 2.1), (3, 1.2), (4, 2.1), (5, 0.01), (6, 0.5), (7, 0.2), (8, 0.6)]
data.sort(key=lambda x:x[1])
print data
>>> [(5, 0.01), (7, 0.2), (6, 0.5), (8, 0.6), (3, 1.2), (2, 2.1), (4, 2.1), (1, 7.57)]
Run Code Online (Sandbox Code Playgroud)
https://www.ics.uci.edu/~pattis/ICS-33/lectures/complexitypython.txt
min_tuple = min([(y, x) for x, y in data])[::-1]
Run Code Online (Sandbox Code Playgroud)
这将反转所有对,min()正常使用(在比较第二个数字之前比较新的第一个数字),然后将所得元组取消反转回原始格式。