Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]
like image 928
user3158105 Avatar asked Mar 21 '23 03:03

user3158105


1 Answers

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.

like image 191
Kevin Avatar answered Mar 23 '23 19:03

Kevin