How to get the largest number from a list?

2
<listados=['31', '1', '3', '2', '5', '26', '3', '3', '1', '14', '2', '1', 
'21', '423', '2', '0', '0', '0', '2', '0', '0', '0', '0', '0', '0', '0', 
'3', '9']
print(max(listados))>

He throws me: 9 it should be 423 The content of the (listings) will be a variable so it would not be useful to look for a grouper directly.

    
asked by Jlcastr 04.10.2018 в 08:31
source

2 answers

1

Your list is a list of chains ( str ), which are sorted according to the lexicographic order, that is, based on the codepoints unicode (in Python 3) of the characters .

Basically the first character of each string is compared and ordered according to its codepoint, if several strings have the same first character the second is compared and so on.

If you have "291" and "2123" the larger string is "291". First, the first character of both chains is compared, both have a "2" so the next one is passed, "9" and "1" (U + 0039 and U + 0031 respectively), as the "9" is greater the comparison ends and the string "291" remains as larger.

If you do not want to lose the type of items in the list (which are still strings) but treat them as integers when obtaining the maximum, minimum or order the simplest is to use the argument key that have max , min , sorted and list.sort . This argument receives a callable object that receives as an argument each item of the iterable to be sorted and whose return is used for that purpose instead of the item itself. In this case we can use the built-in int (or float if some item has decimals):

listados = ['31', '1', '3', '2', '5', '26', '3', '3', '1',
            '14', '2', '1', '21', '423', '2', '0', '0', '0',
            '2', '0', '0', '0', '0','0', '0', '0', '3', '9']
max_item = max(listados, key=int)
>>> max_item
'423'
    
answered by 05.10.2018 / 22:31
source
2

The problem is that your array is an array of string and not numbers so it gives you 9 as a result. You have to do an intermediate step that is to convert that string list to integers.

listados=['31', '1', '3', '2', '5', '26', '3', '3', '1', '14', '2', '1', 
'21', '423', '2', '0', '0', '0', '2', '0', '0', '0', '0', '0', '0', '0', 
'3', '9']

listadosNumero = [int(num) for num in listados]
print (max(listadosNumero))

And if you just want the result it would be:

    listados=['31', '1', '3', '2', '5', '26', '3', '3', '1', '14', '2', '1', 
    '21', '423', '2', '0', '0', '0', '2', '0', '0', '0', '0', '0', '0', '0', 
    '3', '9']
print(max([int(num) for num in listados]))

Greetings.

    
answered by 04.10.2018 в 09:17