简体   繁体   中英

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):
    c=input("").split()
    b.append(c)

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:
        flat_list.append(item)

for i in range(n)
    flat_list[i][2]=int(flat_list[i][2])

b=flat_list.sort()

#not the exact code but something extremely similar

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

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

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

output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM