How can I sort a nested list based on numeric values?

gython :

I have a nested list which looks like this:

raw =  
[[(8, 0.44880571384598744), (17, 0.0403732344197908), 
(13, 0.03796821181062157), (1, 0.03777621092166489), 
(3, 0.02907007584458954), (5, 0.027577126778171947)], 
[(6, 0.24885153810452418), (13, 0.11945937235381485), 
(1, 0.07967490411502279), (7, 0.059837943219436064), 
(11, 0.054917316390175455), (3, 0.05439173103552319), 
(12, 0.042902668032641526), (2, 0.04067120278932331)]]

I want to sort the nested list based on the int at index[0] of every sublist.

But when I try this:

sortraw = []
for line in raw:
    k = sorted(line[0])
    sortraw.append(k)

The lists get sorted by the float value of every sublist and nested list vanishes.

My desired result would be look like this:

[[(1, 0.03777621092166489), (3, 0.02907007584458954), 
(5, 0.027577126778171947), (8, 0.44880571384598744),
(13, 0.03796821181062157), (17, 0.0403732344197908)], 
[(1, 0.07967490411502279), (2, 0.04067120278932331), 
(3, 0.05439173103552319), (6, 0.24885153810452418),
(7, 0.059837943219436064), (11, 0.054917316390175455),  
(12, 0.042902668032641526), (13, 0.11945937235381485)]]

How can I do this?

jamylak :
raw = [[(8, 0.44880571384598744), (17, 0.0403732344197908), 
... (13, 0.03796821181062157), (1, 0.03777621092166489), 
... (3, 0.02907007584458954), (5, 0.027577126778171947)], 
... [(6, 0.24885153810452418), (13, 0.11945937235381485), 
... (1, 0.07967490411502279), (7, 0.059837943219436064), 
... (11, 0.054917316390175455), (3, 0.05439173103552319), 
... (12, 0.042902668032641526), (2, 0.04067120278932331)]]
>>> [sorted(sublist) for sublist in raw]
[[(1, 0.03777621092166489), (3, 0.02907007584458954), (5, 0.027577126778171947), (8, 0.44880571384598744), (13, 0.03796821181062157), (17, 0.0403732344197908)], [(1, 0.07967490411502279), (2, 0.04067120278932331), (3, 0.05439173103552319), (6, 0.24885153810452418), (7, 0.059837943219436064), (11, 0.054917316390175455), (12, 0.042902668032641526), (13, 0.11945937235381485)]]

Or to do it in-place:

for sublist in raw: sublist.sort()

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=10217&siteId=1