[英]How to find a minimum value in a 2D array without using numpy or flattened in Python?
讓我們說:
atable = [[6, 2, 3, 1], [3, 4, 2, 1], [4, 8, 7, 6], [8, 9, 3, 7]]
如果不使用 numpy 或 flattened,您將如何找到整個列表的最小值?
我假設您可以使用列表,但我不確定。
這里有幾種方法:
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)
這是一種蠻力方法:
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)
對於您的具體問題...
min(min(a_table))
正如@Prune 所指出的,這不起作用。 實際上 min(a_table) 返回具有最小第一個元素的子列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.