简体   繁体   English

python key=operator.itemgetter(1)) 如何工作?

[英]How works python key=operator.itemgetter(1))?

I have a matrix and I need to find max element and its number.我有一个矩阵,我需要找到最大元素及其数量。 How to rewrite it without operator (with for)?如何在没有运算符(使用 for)的情况下重写它?

    for j in range(size - 1):
        i, val = max(enumerate(copy[j::, j]), key=operator.itemgetter(1))
        copy = change_rows(copy, j, i)
        P = change_rows(P, j, i) 

And actually maybe you can explain what this string means?实际上,也许您可以解释一下这个字符串的含义?

i, val = max(enumerate(copy[j::, j]), key=operator.itemgetter(1))

Let's decompose this line.让我们分解这条线。

i, val = max(enumerate(copy[j::, j]), key=operator.itemgetter(1))

First, enumerate() creates an iterator over copy[j::,j] that yields index-value pairs.首先, enumerate()copy[j::,j]上创建一个迭代器,生成索引-值对。 For example,例如,

>>> for i, val in enumerate("abcd"):
...     print(i, val)
...
0 a
1 b
2 c
3 d

Next, the max() function is for finding the largest item in a sequence.接下来, max() function 用于查找序列中的最大项目。 But we want it to target the values of copy[j::,j] , not the indices that we are also getting from enumerate() .但是我们希望它针对copy[j::,j]的值,而不是我们也从enumerate()获得的索引。 Specifying key=operator.itemgetter(1) tells max() to look at the (i,val) pairs and find the one with the largest val .指定key=operator.itemgetter(1)告诉max()查看(i,val)对并找到具有最大val的一对。

This is probably better done with np.argmax() , especially because val goes unused.使用np.argmax()可能会更好,特别是因为val未使用。

>>> import numpy as np

>>> for j in range(size - 1):
...     i = np.argmax(copy[j::, j])    # Changed this line.
        copy = change_rows(copy, j, i)
        P = change_rows(P, j, i)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM