Sorting a list of lists by length and by value

list, python

Solution

Try this:

sorted(a, key = lambda x: (len(x), [confrom[card[0]] for card in x]))

ideone

Problem

I have a list of lists: ``` >>> a = [['3D'], ['3D', '4D', '5D'], ['4C'], ['2C'],['4C', '4D'], ['4D'], ['5D'], \ ... ['JC'], ['JC', 'JS'], ['JS']] ``` You may notice that this is card values i.e. C= Clubs etc. J = Jack etc. I also have a reference list: ``` >>> confrom = {'3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, \ ... '0':10, 'J':11, 'Q':12, 'K':13, 'A':14, '2':15} ``` As I am playing a card game where the maximum value is 2. To sort by length of list, I do: ``` >>> a = sorted(a, key = lambda x: len(x)) >>> a ... [['3D'], ['4C'], ['4D'], ['2C'], ['5D'], ['JC'], ['JS'], ['4C', '4D'], ['JC', 'JS'], ['3D', '4D', '5D']] ``` I need to also sort them according to their dictionary value so my resulting list would be: ``` >>> [['3D'], ['4C'], ['4D'], ['5D'], ['JC'], ['JS'], ['2C'], ['4C', '4D'], ['JC', 'JS'], ['3D', '4D', '5D']] ``` Currently this is quite a simple implementation but I want to be able to sort it in a more complicated way.

Original source