矩阵中列的最大值列表(不带Numpy)



我正在尝试获取一个最大值列表​​不带Numpy的矩阵中的列数。我试图写大量的代码,但找不到想要的输出。

这是我的代码:

list=[[12,9,10,5],[3,7,18,6],[1,2,3,3],[4,5,6,2]]
list2=[]
def maxColumn(m, column):   
for row in range(len(m)):
max(m[row][column])  # this didn't work
x = len(list)+1 
for column in range(x):
list2.append(maxColumn(list, column))
print(list2)

这是想要的输出:

[12, 9, 18, 6]

Python有一个内置的zip,它允许您转置1您的列表列表:

L = [[12,9,10,5], [3,7,18,6], [1,2,3,3], [4,5,6,2]]
def maxColumn(L):    
return list(map(max, zip(*L)))
res = maxColumn(L)
[12, 9, 18, 6]

1zip功能的官方描述:

制作一个迭代器,聚合每个可迭代项中的元素。

首先,不要将列表命名为list,因为它会使python的list数据结构在下游代码中变得无用。

带有注释的代码:

my_list=[[12,9,10,5],[3,7,18,6],[1,2,3,3],[4,5,6,2]]
def maxColumn(my_list):
m = len(my_list)
n = len(my_list[0])
list2 = []  # stores the column wise maximas
for col in range(n):  # iterate over all columns
col_max = my_list[0][col]  # assume the first element of the column(the top most) is the maximum
for row in range(1, m):  # iterate over the column(top to down)
col_max = max(col_max, my_list[row][col]) 
list2.append(col_max)
return list2
print(maxColumn(my_list))  # prints [12, 9, 18, 6]

此外,尽管您特别提到了无numpy解决方案,但在numpy中,它就这么简单:

list(np.max(np.array(my_list), axis=0))

也就是说,将my_list转换为numpy数组,然后沿着列找到最大值(轴=0表示您在数组中从上到下移动(。

一种方法是对行进行迭代,并在每个位置(列(保持最大值:

lst = [[12, 9, 10, 5], [3, 7, 18, 6], [1, 2, 3, 3], [4, 5, 6, 2]]
answer = lst[0]
for current in lst[1:]:
answer = [max(x, y) for x, y in zip(answer, current)]
print(answer)

输出:

[12, 9, 18, 6]

另一种方法是首先从给定的行列表中构建列,然后简单地在每列中找到最大值。

您可以使用此函数:

def max_col(my_list):
result = []
i = 0
while i < len(my_list[0]):
max_val = my_list[0][i]
j = 1
while j < len(my_list):
if my_list[j][i] > max_val:
max_val = my_list[j][i]
j += 1
result.append(max_val)
i += 1
return(result)

最新更新