Ironping - 3 months ago 36

Python Question

how do I find the max number in each column of this list please I have figured how to do the row max number but I don't understand the column part

like how it is done here

`import random as rd`

multlst = [[x for x in range(1,5+1)] for y in range(1,5+1)]

def create():

for i in range(len(multlst)):

for j in range(len(multlst[i])):

multlst[i][j]= rd.randint(-100,100)

return multlst

def row():

for i in range(0,len(multlst)):

maxnum = max(multlst[i])

print("The maximum value in row %s is %s"%(i,maxnum))

def col():

## how do I find the maximum value in columns of the list

def main():

create()

print('\n'.join([''.join(['{:4}'.format(item) for item in row])

for row in multlst]))

row()

col()

main()

Answer

Since your multidimensional list appears to be a matrix, you might be better off using numpy and `numpy.max()`

.

For example:

```
import numpy as np
# will return a list of the maximum in each column
np.max(your_array, axis=0)
# will return a list of the maximum in each row
np.max(your_array, axis=1)
```

Alternatively, if you want to remain using the standard library, you could use a generator method inside your `max`

call and ask for the value of the same index in each subsequent row. For example:

```
for col_idx in range(number_of_columns):
maximum = max(multlst[row_idx][col_idx] for row_idx in range(number_of_rows))
print("The maximum value in column %s is %s"%(col_idx,maximum))
```

Or simplified:

```
for col_idx in range(number_of_columns):
maximum = max(row[col_idx] for row in multlst)
print("The maximum value in column %s is %s"%(col_idx, maximum))
```