【问题标题】:Total max of a nested list of arrays in pythonpython中嵌套数组列表的总最大值
【发布时间】:2021-12-03 06:09:55
【问题描述】:

我想要一个获取多个嵌套数组列表并仅返回一个数字的函数:输入中出现的所有数字的全局最大值(或最小值)。

例如:

>>> total_max(3.5,[4.5,1,[2,3], np.random.uniform(size=(5,6)),4],[2,-3])
4.5

我不想在Finding The Largest Number in a Nested List in Pythonpython max of list of arrays 中输出多个数字。而且我希望它也适用于 numpy 数组,Total max of a nested list 并非如此。

【问题讨论】:

  • 一个简单的max(deepflatten(seq)) 就可以解决问题,其中任何deepflatten 都是任何深度展平生成器。在this answer 中可以找到几个不同的扁平化函数的比较。
  • 您的示例不适合 numpy 处理,因为维度大小是可变的(您甚至可以在同一维度上混合使用标量和向量)。
  • @AlainT。在实践中,我不使用随机 numpy 数组,而是使用由其他 numpy 代码计算的 numpy 数组。在我的应用程序中,列表和 numpy 数组的数量不是很大,但是每个 numpy 数组都可以很大。 @Brian:当您只有两个非常大的 numpy 数组时,您是否认为 deepflatten 也比 numpy 快?首先将所有内容展平到列表中可能会降低性能并且可能需要更多内存?

标签: python arrays list max min


【解决方案1】:
import numpy as np

def nested_max(nestedList):
  if not (isinstance(nestedList, list)):
    return np.max(nestedList)
  else:
    return max([nested_max(a) for a in nestedList])

def nested_min(nestedList):
  if not (isinstance(nestedList, list)):
    return np.min(nestedList)
  else:
    return min([nested_min(a) for a in nestedList])

def total_max(*args):
  return max([nested_max(a) for a in args])

def total_min(*args):
  return min([nested_min(a) for a in args])

def total_range(*args):
  return total_min(*args), total_max(*args)

这样得到例如:

>>> total_range(3.5,[4.5,1,[2,3], np.random.uniform(size=(5,6)),4],[2,-3])
(-3, 4.5)

这可用于https://stackoverflow.com/a/42229589 等应用程序中,可以简单地编写:

mi, ma = total_range(dfz, xx)

而不是

mi = np.min((dfz.min(), xx.min()))
ma = np.max((dfz.max(), xx.max()))

查找组合图的整体范围。

有更好的变种吗?例如:支持更多类型的元组、集合、数组和列表?更短的代码?计算效率更高?

【讨论】:

    猜你喜欢
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2016-01-22
    • 2019-06-24
    • 2012-10-25
    • 1970-01-01
    相关资源
    最近更新 更多