我在python 3中编写了这段代码:
matrix = []
loop = True
while loop:
line = input()
if not line:
loop = False
values = line.split()
row = [int(value) for value in values]
matrix.append(row)
print('\n'.join([' '.join(map(str, row)) for row in matrix]))
print('matrix saved')
返回矩阵的一个例子是[[1,2,4],[8,9,0]]。我想知道如何找到矩阵的最大值和最小值?我尝试了python的max(矩阵)和min(矩阵)内置函数,但它不起作用。
感谢您的帮助!
答案 0 :(得分:7)
单线:
最大:
matrix = [[1, 2, 4], [8, 9, 0]]
print (max(map(max, matrix))
9
分钟:
print (min(map(min, matrix))
0
答案 1 :(得分:3)
在剥离列表列表后使用内置函数max()
和min()
:
matrix = [[1, 2, 4], [8, 9, 0]]
dup = []
for k in matrix:
for i in k:
dup.append(i)
print (max(dup), min(dup))
运行如下:
>>> matrix = [[1, 2, 4], [8, 9, 0]]
>>> dup = []
>>> for k in matrix:
... for i in k:
... dup.append(i)
...
>>> print (max(dup), min(dup))
(9, 0)
>>>
答案 2 :(得分:0)
尝试
largest = 0
smallest = 0
count = 0
for i in matrix:
for j in i:
if count == 0:
largest = j
smallest = j
count = 1
if j > largest:
largest = j
if j < smallest:
smallest = j
更新
分裂
largest = 0
count = 0
for i in matrix:
for j in i:
if count == 0:
largest = j
if j > largest:
largest = j
并为最小的
做同样的事情答案 3 :(得分:0)
这是我提出的
M = [[1,2,4],[8,9,0]]
def getMinMax( M ):
maxVal = 0
for row in M:
if max(row) > maxVal: maxVal = max(row)
minVal = maxVal*1
for row in M:
if min(row) < minVal: minVal = min(row)
return ( minVal, maxVal )
getMinMax( M )
// Result: (0, 9) //
答案 4 :(得分:0)
您可以首先决定展平该矩阵,然后找到对应的最大值和最小值,如下所示 将矩阵转换为numpy数组
import numpy as np
matrix = np.array([[1, 2, 4], [8, 9, 0]])
mat_flattened = matrix.flatten()
min_val = min(mat_flattened)
max_val = max(mat_flattened)
答案 5 :(得分:0)
如果要使用将矩阵展平的解决方案,而不是内部循环,则可以使用extend:
big_array = []
for arr in matrix:
big_array.extend(arr)
print(min(big_array), max(big_array))
答案 6 :(得分:0)
如果您不想使用新的数据结构,并且正在寻找尽可能少的代码:
max_value = max([max(l) for l in matrix])
min_value = min([min(l) for l in matrix])
如果您不想两次浏览矩阵:
max_value = max(matrix[0])
min_value = min(matrix[0])
for row in matrix[1:]:
max_value = max(max_value, max(row))
min_value = min(min_value, min(row))