Reputation: 427
a=[(' ', '000'), ('\n', '001000'), ('v', '00100100'), ('O', '0010010100'),('e', '110'), ('n', '1110'), ('r', '1111')]
and i want to sort the list first by the length of the number and then for the alphabetical order of all character that have the same length of number. i have tried to sort by for loop but it just sorts my length of number and not for alphabetical order.
a=[(' ', '000'), ('\n', '001000'), ('v', '00100100'), ('O', '0010010100'),('e', '110'), ('n', '1110'), ('r', '1111')]
for i in range (len(a)):
for j in range(1,len(a)):
if len(a[i][1])>len(a[j][1]):
swap = a[i]
a[i]=a[j]
a[j]=swap
does anyone have any idea ??? thanks in advance
Upvotes: 0
Views: 61
Reputation: 298046
Use the key
argument to sort
:
a.sort(key=lambda item: (len(item[1]), item[0]))
Or more verbosely:
def sort_func(item):
return len(item[1]), item[0]
a.sort(key=sort_func)
Upvotes: 4