如何在此列表的每一列中找到最大数量请知道如何进行行最大数量,但我不理解列部分
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()
答案 0 :(得分:0)
由于您的多维列表似乎是一个矩阵,因此最好使用numpy和numpy.max()
。
例如:
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)
或者,如果您想继续使用标准库,可以在max
调用中使用生成器方法,并在每个后续行中询问相同索引的值。例如:
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))
或简化:
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))