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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With