问题
I have this code wrote in 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')
an example of returned matrix would be [[1,2,4],[8,9,0]].Im wondering of how I could find the maximum and minimum value of a matrix? I tried the max(matrix) and min(matrix) built-in function of python but it doesnt work.
Thanks for your help!
回答1:
Use the built-in functions max()
and min()
after stripping the list of lists:
matrix = [[1, 2, 4], [8, 9, 0]]
dup = []
for k in matrix:
for i in k:
dup.append(i)
print (max(dup), min(dup))
This runs as:
>>> 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:
Try
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
UPDATE
For splitting
largest = 0
count = 0
for i in matrix:
for j in i:
if count == 0:
largest = j
if j > largest:
largest = j
and do the same thing for smallest
回答3:
here is what i came up with
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:
You could first decide to flatten this matrix and then find the corresponding maximum and minimum values as indicated below Convert the matrix to a numpy array
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:
If you are going with the solution of flattening matrix in an array, instead of inner loop you can just use extend:
big_array = []
for arr in matrix:
big_array.extend(arr)
print(min(big_array), max(big_array))
回答6:
If you don't want to use new data structures and are looking for the smallest amount of code possible:
max_value = max([max(l) for l in matrix])
min_value = min([min(l) for l in matrix])
If you don't want to go through the matrix twice:
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))
来源:https://stackoverflow.com/questions/23399801/find-maximum-and-minimum-value-of-a-matrix