gpt4 book ai didi

python - 跨python矩阵的行和列获取最大值

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:41:43 24 4
gpt4 key购买 nike

考虑问题:

The grid is:
[ [3, 0, 8, 4],
[2, 4, 5, 7],
[9, 2, 6, 3],
[0, 3, 1, 0] ]

The max viewed from top (i.e. max across columns) is: [9, 4, 8, 7]
The max viewed from left (i.e. max across rows) is: [8, 7, 9, 3]

我知道如何在 Python 中定义网格:

maximums = [[0 for x in range(len(grid[0]))] for x in range(len(grid))]

获得跨行最大值看起来很容易:

max_top = [max(x) for x in grid]

但是如何获得最大的跨列数呢?

此外,我需要找到一种在线性空间 O(M+N) 中执行此操作的方法,其中 MxN 是矩阵的大小。

最佳答案

使用zip:

result = [max(i) for i in zip(*grid)]

在 Python 中,* 不是指针,而是用于解包传递给对象参数的结构或指定对象可以接收可变数量的项。例如:

def f(*args):
print(args)

f(434, 424, "val", 233, "another val")

输出:

(434, 424, 'val', 233, 'another val')

或者,给定一个可迭代对象,每个项目都可以插入到其相应的函数参数处:

def f(*args):
print(args)

f(*["val", "val3", 23, 23])
>>>('val', 'val3', 23, 23)

zip“转置”数据列表,即每一行变成一列,反之亦然。

关于python - 跨python矩阵的行和列获取最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49518496/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com