I just starting out in Python after a long absence from the programming language and I am writing a program which reads from a file to retrieve values. Currently I've got the program in question to read from the file and put certain values into a tuple, however, the problem I am now facing is returning the min and max values from my list of tuples in python, the list of values I have in the tuple list is:
tuple = ('44.0', '34.0', '17.0', '6.0','15.0')
However when I use max to call max(tuple) i am greeted with 6.0 as my result rather than the correct answer of 44.0. Likewise if I try to return the minimum value by using min(tuple). I am instead given the value of 15.0 rather than the correct value of 6.0.
Please, would you be able to advise how I can resolve this so that I can return the correct values?
Comparisons on strings are lexicographical, by default. This means that "9" is lexicographically greater than "10", because the ASCII value of "9" (57) is greater than the ASCII value of "1" (49), and so on.
If you want to compare these string values by their actual numeric value, you'll have to pass a key argument to max/min:
max(tupple, key=float)
# '44.0'
min(tupple, key=float)
# '6.0'
Of course, this requires all your tuple values to be string representation of floats/ints. If you have a non-numeric string ('abc', for example), this is not going to work.
You are getting '6.0' as the maximum value because you are actually comparing strings and not integers/floats.
String comparisons are lexicographical, and hence you get '6.0' as the maximum value.
You can pass a key parameter so that the comparisons are arithmetic and not lexicographical, like this:
max(yourTupple, key = float)
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