Python why max (max (float_2d_array)) is giving the wrong answer?

eg:

a = [[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], 
 [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], 
 [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], 
 [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], 
 [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], 
 [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], 
 [0.0, 0.0, 1.2852976787772832, 0.7965388321000092, 0.0, 0.0, 0.0, 0.0, 0.0],
 [0.0, 0.0, 0.0, 6.409872844109646, 0.17506688391255013, 0.0, 0.0, 0.0, 0.0],
 [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], 
 [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], 
 [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], 
 [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], 
 [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]
print max(max(a))
print max(a)

      

Result:

+1.28529767878

[0.0, 0.0, 1.2852976787772832, 0.7965388321000092, 0.0, 0.0, 0.0, 0.0, 0.0]

This is clearly incorrect, the maximum value should be 6.409872844109646.

b = []
for i in a:
    b.extend(i)
print max(b)

      

+6.40987284411

This is python 2.7, Cpython.

Many thanks.

+3


source to share


2 answers


The lists are sorted by item. Since the index 1.2852976787772832

is in one place earlier than in the 6.409872844109646

candidate sublist, the list containing the first is selected as the maximum.

In the same index in the second list, we have 0

and are 1.2852976787772832

clearly greater than 0:

[0.0, 0.0, 1.2852976787772832, 0.7965388321000092, 0.0, 0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 6.409872844109646, 0.17506688391255013, 0.0, 0.0, 0.0, 0.0]
#           ^ here your tie-breaker 

      



In fact, the next index containing 6.4...

is never checked.

I'm not sure how you expect the maximum sublist to be selected: the sublist with the maximum amount, the sublist containing the maximum number? You will have to code the behavior you want, unless the default behavior has shortened it.

+6


source


Moses already explained why you got the wrong result: the first item is larger than the other and "wins" when comparing lists.

To get the maximum value, you have to flatten the list:



print(max(x for l in a for x in l))

      

+1


source







All Articles