Reputation: 53
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
Upvotes: 0
Views: 47
Reputation: 12679
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']]
Upvotes: 2
Reputation: 363043
Sort using a custom key. You can use an anonymous function:
data.sort(key=lambda s: int(s[2]))
Upvotes: 3