-1

I want to get the maximum value from a list.

List = ['1.23','1.8.1.1']
print max(List)

If I print this I'm getting 1.8.1.1 instead of 1.23. What I am doing wrong?

julienc
  • 19,087
  • 17
  • 82
  • 82
harika
  • 11
  • 1
  • 2

3 Answers3

1

The easiest way is, to use tuple comparison.
Say:

versions = ['1.23','1.8.1.1']

def getVersionTuple(v):
    return tuple(map(int, v.strip().split('.')))

Now you can use, print(max(map(getVersionTuple, versions))) to get the maximum.

EDIT:

You can use '.'.join(map(str, m)) to get the original string (given m holds the max tuple).

Wickramaranga
  • 943
  • 2
  • 19
  • 35
0

These aren't numbers, they are strings, and as such they are sorted lexicographically. Since the character 8 comes after 2, 1.8.1.1 is returned as the maximum.

One way to solve this is to write your own comparing function which takes each part of the string as an int and compares them numerically:

def version_compare(a, b):
    a_parts = a.split('.')
    b_parts = b.split('.')
    a_len = len(a_parts)
    b_len = len(b_parts)
    length = min(a_len, b_len)

    # Compare the parts one by one
    for i in range(length):
        a_int = int(a_parts[i])
        b_int = int(b_parts[i])

        # And return on the first nonequl part
        if a_int != b_int:
            return a_int - b_int

    # If we got here, the longest list is the "biggest"
    return a_len - b_len

print sorted(['1.23','1.8.1.1'], cmp=version_compare, reverse=True)[0]
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • Why do you need to sort? This function with slight updating can give max itself – xyz Sep 17 '16 at 09:25
0

A similar approach - assuming these strings are version numbers - is to turn the version string to an integer list:

vsn_list=['1.23', '1.8.1.1']
print sorted( [ [int(v) for v in x.split(".")] for x in vsn_list ] )

When you compare strings, they are compared character by character so any string starting with '2' will sort before a string starting with '8' for example.

John D
  • 1,627
  • 1
  • 11
  • 10