2

let's say i have a list of strings like this

L = ['5', '3', '4', '1', '2', '2 3 5', '2 4 8', '5 22 1 37', '5 22 1 22', '5 22 1 23', ....]

How can i sort this list so that i would have something like this:

L = ['1', '2', '3','4', '5', '2 3 5', '2 4 8', '5 22 1 22', ' 5 22 1 23', '5 22 1 37', ...]

basically i need to order the list based on the first different number between 2 strings

2
  • Does the length of the string really matter? Where would '4 2' appear in your result, before or after '5'? Commented Dec 21, 2018 at 14:02
  • yes the lenght matters, so '4 2' would be after 5 Commented Dec 21, 2018 at 14:08

2 Answers 2

5

You could sort using a tuple:

L = ['5', '3', '4', '1', '2', '2 3 5', '2 4 8', '5 22 1 37', '5 22 1 22', '5 22 1 23']

result = sorted(L, key=lambda x: (len(x.split()),) + tuple(map(int, x.split())))

print(result)

Output

['1', '2', '3', '4', '5', '2 3 5', '2 4 8', '5 22 1 22', '5 22 1 23', '5 22 1 37']

The idea is to use as key a tuple where the first element is the amount of numbers in the string and the rest is the tuple of numbers. For example for '2 3 5' the key is (3, 2, 3, 5)

As suggested by @PM2Ring you could use a def function instead of a lambda:

def key(x):
    numbers = tuple(map(int, x.split()))
    return (len(numbers),) + numbers
Sign up to request clarification or add additional context in comments.

2 Comments

Maybe use a def function instead of a lambda for the key function so you don't have to call x.split twice on each item.
Once Python 3.8 comes out, you could write lambda x: (len(y:=x.split()),) + tuple(map(int, y))). (Personally, I'd still pre-define the function, but there appear to be people who like the syntax that PEP-572 settled on.)
1

A slightly different approach than @Daniel's one.

idx = sorted(range(len(L)), key=lambda i: int(''.join(L[i].split())))
L = [L[i] for i in idx]

output

['1',
 '2',
 '3',
 '4',
 '5',
 '2 3 5',
 '2 4 8',
 '5 22 1 22',
 '5 22 1 23',
 '5 22 1 37']

Comments

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.