Sort a list of strings based on 2 criteria

SoftTimur :

I have a list of strings.

I would like to sort them based on 2 criteria:

  • from small length to large length
  • if the length of 2 strings are same, then sort by < of string values

Does anyone know how to achieve that in Python?

I tried

def cmp(a,b):
    if len(a) < len(b):
        return -1
    elif len(a) > len(b):
        return 1
    elif a < b:
        return -1
    elif a > b:
        return 1
    else:
        return 0

myList.sort(lambda x,y: cmp(x, y))

But it gave me an error TypeError: sort() takes no positional arguments.

Mark Meyer :

You don't really need all the branching. The pythonic way is to just return a tuple which will sort in the order of the tuple:

s = ['twenty', 'three', 'two','one',  'four']

sorted(s, key=lambda w: (len(w), w))
# ['one', 'two', 'four', 'three', 'twenty']

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=386445&siteId=1