Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a list of lists by length and by value

Tags:

python

list

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.

like image 672
tcatchy Avatar asked May 24 '12 04:05

tcatchy


1 Answers

Try this:

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

ideone

like image 71
Mark Byers Avatar answered Oct 04 '22 16:10

Mark Byers