python快速求一个数组的最大值/最小值及其索引 - 宥宁

python

python快速求一个数组的最大值/最小值及其索引

enumerate()函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标。

x = [3, 2.2, 7.4, 6, 4]

list(enumerate(x))

# 输出 [(0, 3), (1, 2.2), (2, 7.4), (3, 6), (4, 4)]

operator.itemgetter()函数用于获取对象的哪些维的数据,参数为想要取的一些维度序号。

x = [3, 2.2, 7.4, 6, 4]

b1 = operator.itemgetter(2, 1)

b1(x) # 输出 (7.4, 2.2)

b2 = operator.itemgetter(3)

b2(x) # 输出 6

最后max()函数有一个应用很巧妙的参数key,在这里定义为operator.itemgetter(1),表示对enumerate(x)每个元素的第一维做比较(从0维开始),然后返回第一维值最大的元素,即包含索引和数值。

x = [3, 2.2, 7.4, 6, 4]

min_index, min_number = min(enumerate(x), key=operator.itemgetter(1))

# min_index=1, min_number =2.2

max_index, max_number = max(enumerate(x), key=operator.itemgetter(1))

# max_index=2, max_number = 7.4

 还有另一个简单且low的方法,index()函数返回参数在数组中第一次出现的索引的值,如果数组中不含有这个参数,则抛出异常。

num = [4,1,2,3,4]

max = max(num)

max_index = num.index(max)

#max_index=0

 

借鉴于:https://blog.csdn.net/qq_15056979/article/details/89194723

 

以上是 python快速求一个数组的最大值/最小值及其索引 - 宥宁 的全部内容, 来源链接: utcz.com/z/389057.html

回到顶部