python - 以递归方式对Python列表进行排序

标签 python python-2.7 sorting

作为输入,我将获得最多可达 n 级的列表列表,并且每次都会有所不同。假设,我有一个列表

[[2, 1, 3], 4, [2, 3], 7, 1, [9, [4, 2], 5]]

这里我想对此列表进行排序,预期输出是

[1, 4, [2, 3], [1, 2, 3], 7, [5, [2, 4], 9]]

这里,首先根据元素进行排序,然后根据列表内元素的总和进行排序。

代码:

input_freq = [[2,1,3],4,[2,3],7,1,[9,[4,2],5]]

res = []

def sortFreq(input_freq):
    elements = []
    list_of_elements = []

    for each in input_freq:
        if isinstance(each, list):
            print "list"
            list_of_elements.append(each)
            each.sort()
        else:
            elements.append(each)
            elements.sort()

    print elements
    print list_of_elements

sortFreq(input_freq)

预期输出:

[1, 4, [2, 3], [1, 2, 3], 7, [5, [4, 2], 9]]

但是我的代码返回错误的结果:

[[1, 2, 3], [2, 3], [5, 9, [4, 2]]]

最佳答案

您必须首先向下移动到嵌套级别,然后在递归调用返回时对父级别进行排序。我假设您想要返回一个新列表(而不是就地排序):

def nested_sort(l):
    def sort_key(e):
        if isinstance(e, list):
            return sum(sort_key(inner) for inner in e)
        return e
    return sorted(
        [nested_sort(e) if isinstance(e, list) else e for e in l],
        key=sort_key)

排序键必须对嵌套列表进行递归求和,因此如果您有许多嵌套级别,这可能会很昂贵。因为可能值得根据求和列表的标识添加缓存:

def nested_sort(l, _sum_cache=None):
    if _sum_cache is None:
        _sum_cache = {}
    def sort_key(e):
        if isinstance(e, list):
            e_id = id(e)
            if e_id not in _sum_cache:
                _sum_cache[e_id] = sum(sort_key(inner) for inner in e)
            return _sum_cache[e_id]
        return e
    return sorted(
        [nested_sort(e, _sum_cache) if isinstance(e, list) else e for e in l],
        key=sort_key)

演示:

>>> nested_sort([[2, 1, 3], 4, [2, 3], 7, 1, [9, [4, 2], 5]])
[1, 4, [2, 3], [1, 2, 3], 7, [5, [2, 4], 9]]

关于python - 以递归方式对Python列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47710068/

相关文章:

php - 如何通过 php/mysql 对我的日期进行排序?

python - Ipython 笔记本输出静音

python - 使用 python 将列表中的单引号元素转换为双引号

mysql - 类型错误 : not all arguments converted during string formatting

c - (C程序)随机数数组程序,并按升序排序,然后求中位数

javascript - 按数字和字典顺序对多维数组进行排序javascript

python - 字符串的常量部分

python - 如何从文件中读取带有字符串键和元组值的字典?

python - Python 中的模糊查找

python - 在 python linux 中执行命令时在 python 中给出响应 os.system()