简体   繁体   English

如何根据数值对嵌套列表进行排序?

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

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.我想根据每个子列表的 index[0] 处的 int 对嵌套列表进行排序。

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?我怎样才能做到这一点?

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

如果您不想对整个raw列表进行排序,可以使用:

list(map(sorted, raw)

You can use a lambda function instead:您可以改用 lambda 函数:

print(list(map(lambda x:sorted(x), raw)))

output :输出 :

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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