对包含各种元素的嵌套列表进行排序

Sorting Nested Lists with Various Elements

提问人:BlueInundation 提问时间:12/4/2022 最后编辑:BlueInundation 更新时间:12/4/2022 访问量:47

问:

我有一个嵌套列表,如下所示:

[["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,但我只是不知道该怎么做。通过网络和这个网站搜索,但我就是做不到。

python python-3.x 列表 排序 嵌套列表

评论

0赞 Alex Hall 12/4/2022
首先编写一个函数,该函数从一个子列表中提取 x 的值。如果您不确定如何做到这一点,请尝试仅获取以 x 开头的字符串,例如它应该返回“x=17”。

答:

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