代码之家  ›  专栏  ›  技术社区  ›  jxie0755

sum()如何用于合并列表

  •  0
  • jxie0755  · 技术社区  · 7 年前

    def tree(label, branches=[]):
        return [label] + list(branches)
    
    def label(tree):
        return tree[0]
    
    def branches(tree):
        return tree[1:]
    

    有一个函数可以将树的所有节点提取到列表中:

    def all_nodes(tree):
        return [label(tree)] + sum([all_nodes(b) for b in branches(tree)], [])
    
    T = tree(1, [tree(2, [tree(4), tree(5)]), tree(3, [tree(6), tree(7)])])
    print(all_nodes(T))
    # >>> [1, 2, 4, 5, 3, 6, 7]
    

    你可以看出这很有效,但我搞不懂 sum() 在这里使用。

    我知道一个列表可以添加到另一个列表:

    print([1] + [2]) # >>> [1, 2]
    

    求和() :

    a, b = [1], [2]
    print(sum(a, b))
    # >>> TypeError: can only concatenate list (not "int") to list
    print(sum([a, b]))
    # >>> TypeError: unsupported operand type(s) for +: 'int' and 'list
    

    tree 函数,如何 求和()

    2 回复  |  直到 7 年前
        1
  •  1
  •   Prune    7 年前

    sum 对一系列元素进行操作,例如 sum([1, 2, 3]) (生产 6 )或者 sum([ [1], [2] ], []) (生产 [1, 2] ). 有一个可选的第二个参数 start 价值。例如, sum([1, 2, 3], 10) 从10开始计算,假设 16 开始 默认为 0 :如果要对非数字对象求和,则必须提供 开始 价值。

    当你给它的时候 sum(a, b) ,列表 a 总和 did是(正确地)遍历该列表的项,将它们添加到 你提供的价值。逻辑是这样的:

    result = b
    for element in a:
        result = result + element
    

    因此,你要做的第一件事就是 result = [2] + 1 . 记住,第一个论点是 序列

    sum([a], b)
    

    产生 [2, 1] b 是起始值。

        2
  •  1
  •   Olivier Melançon iacob    7 年前

    内建方法 sum +

    默认情况下,起始值为 0 ,含义 sum([[1], [2]]) 相当于 0 + [1] + [2] 它引发了 TypeError .

    要连接希望初始值为 [] ,空列表。那么, sum([[1], [2], [3]], []) [] + [1] + [2] + [3] 如所愿。

    性能

    不建议使用 列表已创建。相反,您希望使用遍历所有列表并将项目附加到新列表的解决方案。

    def concat_lists(lists):
        new_list = []
        for l in lists:
            new_list.extend(l)
    

    或者使用 itertools .

    from itertools import chain
    
    new_list = list(chain(*lists))