Alberto
Alberto

Reputation: 25

Sorting a list of strings with a specific method

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

Upvotes: 2

Views: 89

Answers (2)

Dani Mesejo
Dani Mesejo

Reputation: 61910

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

Upvotes: 5

Ghilas BELHADJ
Ghilas BELHADJ

Reputation: 14096

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']

Upvotes: 1

Related Questions