I have a matrix and I need to find max element and its number. How to rewrite it without operator (with 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. 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. But we want it to target the values of copy[j::,j]
, not the indices that we are also getting from enumerate()
. Specifying key=operator.itemgetter(1)
tells max()
to look at the (i,val)
pairs and find the one with the largest val
.
This is probably better done with np.argmax()
, especially because val
goes unused.
>>> 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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.