简体   繁体   English

如何在不使用 numpy 或在 Python 中展平的情况下在二维数组中找到最小值?

[英]How to find a minimum value in a 2D array without using numpy or flattened in Python?

Let's say that:让我们说:

atable = [[6, 2, 3, 1], [3, 4, 2, 1], [4, 8, 7, 6], [8, 9, 3, 7]]

without using numpy or flattened, how would you find the minimum value of the entire list?如果不使用 numpy 或 flattened,您将如何找到整个列表的最小值?

I assume you can use a list but I am not sure.我假设您可以使用列表,但我不确定。

Here are several approaches:这里有几种方法:

from itertools import chain

atable = [[6, 2, 3, 1], [3, 4, 2, 1], [4, 8, 7, 6], [8, 9, 3, 7]]

# Flatten the sublists into a single list
result = min(chain.from_iterable(atable))

# Find the min of each list, the find the min of mins
result = min(map(min, atable))

# Use a generator expression with nested loops
result = min(i for lst in atable for i in lst)

Here is a brute force approach:这是一种蛮力方法:

atable = [[6, 2, 3, 1], [3, 4, 2, 1], [4, 8, 7, 6], [8, 9, 3, 7]]
min_list = []
for l in atable:
    min_list.append(min(l))
min_val = min(min_list)

For your specific problem...对于您的具体问题...

min(min(a_table))

As noted by @Prune this does not work.正如@Prune 所指出的,这不起作用。 In fact min(a_table) returns the sublist with the smallest first element.实际上 min(a_table) 返回具有最小第一个元素的子列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM