简体   繁体   中英

How can I grab the highest value in alphanumeric list using Python?

If I have a list of strings such as ["A", "B", "1", "0", "C", "2"] , how can I have Python elegantly grab the "highest" value ( 2 ) of that list?

For example, if the list above were to be sorted from lowest to highest, it would be

[A, B, C, 0, 1, 2]

and I would need to grab 2 .

using sorted() , organises the list in the following way

[0, 1, 2, A, B, C]

You could provide a custom key to sorted that causes nondigit characters to appear before digits:

>>> x = ["A", "B", "1", "0", "C", "2"]
>>> sorted(x, key = lambda item: (item.isdigit(), item))
['A', 'B', 'C', '0', '1', '2']
>>> max(x, key = lambda item: (item.isdigit(), item))
'2'

A more general solution could be to explicitly specify the kind of ordering you want. This makes it easy to change the implementation if you change your mind on what is "highest".

>>> ordering = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
>>> x = ["A", "B", "1", "0", "C", "2"]
>>> print max(x, key=ordering.index)
2

>>> #Actually, I've decided that A should be highest!
>>> ordering = "BCDEFGHIJKLMNOPQRSTUVWXYZ0123456789A"
>>> print max(x, key=ordering.index)
A

This may be a little slower than the first solution, since index runs in linear time, but you may find the tradeoff worthwhile if you feel it makes the code more understandable.

my_list = ["A", "B", "1", "0", "C", "2"]
my_list.sort()
print(my_list[-1])

However, this will print "C". Letters are "greater than" numbers in ASCII

Do you want to consider numbers 'higher than' letters?

a = ["A", "B", "1", "0", "C", "2"]
max([x for x in a if x.isdigit()])

This iterates over the list and sets the value of max to the the value of each if each is anumber and greater than the current value of max:

max = 0
for item in lst:
    if not item.isalpha():
        if int(item) > max:
            max = int(item)
        else:
            pass

print(max)

If your goal is to get the largest number among the elements of your list, you could try casting the numbers to integers and then finding the maximum.

def casted_max(l):
    casted = [int(m) for m in l if m.isdigit()]
    if casted:
        return max(casted)
    else:
        return -1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM