python-3.x 对具有各种元素的嵌套列表进行排序

uurity8g  于 2022-12-05  发布在  Python
关注(0)|答案(2)|浏览(157)

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

[["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,但我就是想不出怎么做。在网上和这个网站上搜索,但我就是做不到。

xhv8bpkk

xhv8bpkk1#

根据您的列表:

sort_this_list = [
    ["bla","blabla","x=17"],
    ["bla","x=13","z=13","blabla"],
    ["x=27","blabla","bla","y=24"]
]

首先,从相应的列表中提取x元素!

def get_x(list):
    # Iterate over the items in the given list
    for item in list:
        # Check if the item starts with "x="
        if item.startswith("x="):
            # Extract the value of x and return it as an integer
            return int(item.split("=")[1])

现在,您可以通过sorted_ascending = sorted(sort_this_list, key=get_x)对其进行排序(查找sorted(..)函数:这将按照您的请求以升序返回它。)!

gojuced7

gojuced72#

为了方便起见,这里有一个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']]

相关问题