【问题标题】:Sorting Nested Lists with Various Elements对包含各种元素的嵌套列表进行排序
【发布时间】:2022-12-04 19:31:41
【问题描述】:

我有一个嵌套列表,例如:

[["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 但我不知道该怎么做。通过网络和本网站进行搜索,但我做不到。

【问题讨论】:

  • 首先编写一个函数,从一个子列表中提取 x 的值。如果您不确定该怎么做,请尝试只获取以 x 开头的字符串,例如它应该返回“x=17”。

标签: python python-3.x list sorting nested-lists


【解决方案1】:

鉴于您的清单:

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(..) 函数:这将按照您的要求将其升序返回。)!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-17
    • 2017-02-08
    • 2010-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-06
    相关资源
    最近更新 更多