0
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

1
  • Is this for a class? Python has a few sort methods built in. Commented Apr 29, 2013 at 6:02

1 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

2 Comments

@TommyNgo: See if the more verbose way of writing it helps.
@TommyNgo: I'm not sure how else to explain it. It sorts each element by using the output of sort_func(element) instead of the element itself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.