How can I sort sublists that are part of a list based on a single var from the sublist?

I'm interested in sorting a list that's formed from several sublists.

For example, I'm receiving as input the following:

Rus Dan 264
Pop Alin 263
Stan Darius 304
Pop Tudor 252
Rusu Alin 323
Stroe Mihai 279
Rusu Paul 268

I'm reading the lines:

for i in range(n):

The result I get is:

[['Rus', 'Dan', '264'], ['Pop', 'Alin', '263'], ['Stan', 'Darius', '304'], ['Pop', 'Tudor', '252'], ['Rusu', 'Alin', '323'], ['Stroe', 'Mihai', '279'], ['Rusu', 'Paul', '268']]

I'm interested in ordering the sublists by the last number, not by char.

Any suggestions please?

I've tried to split the sublists then to make the last number int and order each sublist using .sort() but I've got several errors.

for sublist in n:
    for item in sublist:

for i in range(n)


#not the exact code but something extremely similar

2 answers

  • answered 2018-03-13 21:05 wim

    Sort using a custom key. You can use an anonymous function:

    data.sort(key=lambda s: int(s[2]))

  • answered 2018-03-13 21:11 Ayodhyankit Paul

    Try this :

    data=[['Rus', 'Dan', '264'], ['Pop', 'Alin', '263'], ['Stan', 'Darius', '304'], ['Pop', 'Tudor', '252'], ['Rusu', 'Alin', '323'], ['Stroe', 'Mihai', '279'], ['Rusu', 'Paul', '268']]
    print(sorted(data,key=lambda x:int(x[-1])))


    [['Pop', 'Tudor', '252'], ['Pop', 'Alin', '263'], ['Rus', 'Dan', '264'], ['Rusu', 'Paul', '268'], ['Stroe', 'Mihai', '279'], ['Stan', 'Darius', '304'], ['Rusu', 'Alin', '323']]