是否有一行代码来查找矩阵中的最大值? [英] Is there a one line code to find maximal value in a matrix?

查看:178
本文介绍了是否有一行代码来查找矩阵中的最大值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  ans =要找到数字矩阵中的最大值,我们可以编写5行来解决问题:矩阵[0] [0] 
在范围内(len(矩阵)):
在范围内(len(矩阵[0])):
ans = max(ans,矩阵[x] [y])
返回ans

这个问题?
实际上我觉得这很尴尬:

$ $ $ $ $ $ $ $ $ return max(max(matrix,key = max ))

  return max(map(max,matrix))


解决方案

您可以使用生成器表达式来查找最大值你的矩阵。这样可以避免在内存中构建完整的矩阵元素列表。

  maximum = max(max(row)for row in矩阵)

而不是列表理解,如前面的答案

  maximum = max([max(row)for行中矩阵])

这是来自PEP( rationale section):

lockquote

...许多用例不需要在
内存中创建完整列表。相反,它们只需要在
时间迭代元素。

...



生成器表达式对于像sum(),min()和max()这样的函数特别有用,这些函数将可迭代的输入减少为单个值。

如果和sum(),min()和 max()等简化函数结合使用,则生成器表达式的效用会大大增强。

另外,看看这个SO帖子:生成器表达式与列表理解


To find the maximal value in a matrix of numbers, we can code 5 lines to solve the problem:

ans = matrix[0][0]
for x in range(len(matrix)):
    for y in range(len(matrix[0])):
        ans = max(ans, matrix[x][y])
return ans

Is there a one line solution for this problem? The one that I came up with is pretty awkward actually:

return max(max(matrix, key=max))

or

return max(map(max, matrix))

解决方案

You can use generator expression to find the maximum in your matrix. That way you can avoid building the full list of matrix elements in memory.

maximum = max(max(row) for row in matrix)

instead of list comprehension as given in a previous answer here

maximum = max([max(row) for row in matrix])

This is from PEP (the rationale section):

...many of the use cases do not need to have a full list created in memory. Instead, they only need to iterate over the elements one at a time.

...

Generator expressions are especially useful with functions like sum(), min(), and max() that reduce an iterable input to a single value

...

The utility of generator expressions is greatly enhanced when combined with reduction functions like sum(), min(), and max().

Also, take a look at this SO post: Generator Expressions vs. List Comprehension.

这篇关于是否有一行代码来查找矩阵中的最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆