📜  Python – 每列的最大值

📅  最后修改于: 2022-05-13 01:55:12.182000             🧑  作者: Mango

Python – 每列的最大值

有时,我们会遇到这样的问题,我们需要找到矩阵中每一列的最大值,即列表列表中每个索引的最大值。这种问题在竞争性编程中非常常见和有用。让我们讨论一些可以解决这个问题的方法。

方法 #1:使用max() + list comprehension + zip()
需要结合上述方法来解决这个特定问题。 max函数用于获取所需的最大值, zip函数提供类似索引的组合,然后使用列表推导创建列表。

# Python3 code to demonstrate
# Maximum of each Column
# using max() + list comprehension + zip()
  
# initializing list
test_list = [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
  
# printing original list
print("The original list : " + str(test_list))
  
# using max() + list comprehension + zip()
# Maximum of each Column
res = [max(idx) for idx in zip(*test_list)]
  
# print result
print("The Maximum of each index list is : " + str(res))
输出 :
The original list : [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
The Maximum of each index list is : [9, 7, 6]

方法 #2:使用map() + max() + zip()
这与上述方法的工作方式几乎相似,但不同之处在于我们使用 map函数来构建最大元素列表,而不是使用列表推导。

# Python3 code to demonstrate
# Maximum index value
# using max() + map() + zip()
  
# initializing list
test_list = [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
  
# printing original list
print("The original list : " + str(test_list))
  
# using max() + map() + zip()
# Maximum index value
res = list(map(max, zip(*test_list)))
  
# print result
print("The Maximum of each index list is : " + str(res))
输出 :
The original list : [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
The Maximum of each index list is : [9, 7, 6]