提问人:BlueInundation 提问时间:12/4/2022 最后编辑:BlueInundation 更新时间:12/4/2022 访问量:47
对包含各种元素的嵌套列表进行排序
Sorting Nested Lists with Various Elements
问:
我有一个嵌套列表,如下所示:
[["bla","blabla","x=17"],["bla","x=13","z=13","blabla"],["x=27","blabla","bla","y=24"]]
我需要按 x(从最少到最多)将其排序为(其他字符串应保留在原处):
[["bla","x=13","z=13","blabla"],["bla","blabla","x=17"],["x=27","blabla","bla","y=24"]]
以及从多到少:
[["x=27","blabla","bla","y=24"],["bla","blabla","x=17"],["bla","x=13","z=13","blabla"]]
我想我必须使用 key=lambda,但我只是不知道该怎么做。通过网络和这个网站搜索,但我就是做不到。
答:
0赞
Swifty
12/4/2022
#1
为了方便起见,这里有一个带有 lambda 函数的函数:
mylist = [["bla","blabla","x=17"],["bla","x=13","z=13","blabla"],["x=27","blabla","bla","y=24"]]
mylist.sort(key = lambda l:int([item for item in l if 'x=' in item][0].split('=')[1]), reverse = True)
# [['x=27', 'blabla', 'bla', 'y=24'],
# ['bla', 'blabla', 'x=17'],
# ['bla', 'x=13', 'z=13', 'blabla']]
评论