simone13
simone13

Reputation: 31

sorting a list of lists from shortest to longest

i have to order a list of lists of numbers from shortest to longest. At equality of lenght, in ascending order.

input=[[19, -3, 2, -10, -20], [22, 2, -10, -20], [19, -3, 12, -20], [19, -3, 2, 10], [20, -10, -20], [22, 12, -20], [22, 2, 10], [30, -20], [20, 10], [50], [10], [10, -20], [22, 32], [30], [19, -3, 32]]

expected output:

[(10,), (30,), (50,), 
    (10, -20), (20, 10), (22, 32), (30, -20), 
    (19, -3, 32), (20, -10, -20), (22, 2, 10), (22, 12, -20), 
    (19, -3, 2, 10), (19, -3, 12, -20), (22, 2, -10, -20), 
    (19, -3, 2, -10, -20)]

Upvotes: 1

Views: 963

Answers (3)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

It seems that you need to sort by length and a tuple itself to get the expected result:

input_lst = [[19, -3, 2, -10, -20], [22, 2, -10, -20], [19, -3, 12, -20], [19, -3, 2, 10], [20, -10, -20], [22, 12, -20], [22, 2, 10], [30, -20], [20, 10], [50], [10], [10, -20], [22, 32], [30], [19, -3, 32]]
res = sorted(input_lst, key=lambda x: (len(x), x))
print(res)

The output:

[[10], [30], [50], [10, -20], [20, 10], [22, 32], [30, -20], [19, -3, 32], [20, -10, -20], [22, 2, 10], [22, 12, -20], [19, -3, 2, 10], [19, -3, 12, -20], [22, 2, -10, -20], [19, -3, 2, -10, -20]]

If you actually need to get a result as a list of tuples change the crucial line to the following:

res = sorted(map(tuple, input_lst), key=lambda x: (len(x), x))

Upvotes: 1

Sunitha
Sunitha

Reputation: 12015

Just sort it with a custom key which would sort based on sublist length and use the values of the list for lists of same length

>>> input.sort(key=lambda l: (len(l), l))
>>> print (*input, sep='\n')
[10]
[30]
[50]
[10, -20]
[20, 10]
[22, 32]
[30, -20]
[19, -3, 32]
[20, -10, -20]
[22, 2, 10]
[22, 12, -20]
[19, -3, 2, 10]
[19, -3, 12, -20]
[22, 2, -10, -20]
[19, -3, 2, -10, -20]

Upvotes: 0

Saritus
Saritus

Reputation: 978

The answer your looking for is

sorted(input, key=lambda l: (len(l), l))

Upvotes: 2

Related Questions