-3

I have a list of strings in the below format:

['b-3','a-2','c-4','d-2']

Need to sort in such a way that list is sorted by the number (following -). If the numbers are equal, the string needs to be sorted in alphabetical order. Output should be

['a-2','d-2','b-3','c-4']

I can easily achieve in JAVA using comparator / comparable. How to achieve this by writing the function in python.

list.sort(key= )

import sys
from collections import Counter, OrderedDict
def sortfunc(item):
    key,value = item.split('-')
    return value


if __name__ == "__main__":
    s = input().strip()
    c = Counter(s)

    lst = []

    for key in c:
        lst.append(key+'-'+str(c[key]))

    lst.sort(key=lambda x :sortfunc(x), reverse=True)
    print(lst)

gives the output as:

['b-3', 'c-2', 'a-2', 'e-1', 'd-1']

Now, I need help to enhance sortFunc is such as way - if the count of characters are equal, then the string needs to be sorted in alphabetical order.

1 Answers1

1

This is one way.

lst = ['b-3', 'a-2', 'c-4', 'd-2']

res = sorted(lst, key=lambda x: (lambda y: (int(y[1]), y[0]))(x.split('-')))

# ['a-2', 'd-2', 'b-3', 'c-4']

Explanation

  • Use sorted with key argument and a custom lambda function.
  • Tuple comparisons are performed in order of tuple index.
  • Remember to convert the first tuple value to int for integer comparison.
  • You cannot use x.split('-')[::-1] directly as you need to convert one of the values to int.
jpp
  • 134,728
  • 29
  • 196
  • 240
  • These downvotes are harsh. If it's because it's a dupe, at least DV the question as well- or leave a comment! I think sometimes people like to jump on the bandwagon. This is a good answer. – pault Apr 04 '18 at 17:46
  • @vaultah, updated with an unhealthy one-liner with single split :). – jpp Apr 04 '18 at 21:44