sum()如何用于合并列表

2024-04-18 00:08:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习python中的树,我用这些函数来构建树:

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]

但是我不能用sum()来实现它:

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函数中,sum()是如何合并所有列表的?你知道吗


Tags: 函数tree列表forreturndefalllabel
2条回答

内置方法sum将使用+操作对元素列表求和。它的第二个参数是起始值。你知道吗

默认情况下,起始值是0,这意味着sum([[1], [2]])等同于0 + [1] + [2],这会引发TypeError。你知道吗

要串联列表,您希望初始值为[],一个空列表。然后,sum([[1], [2], [3]], [])根据需要等价于[] + [1] + [2] + [3]。你知道吗

性能

不建议使用sum连接列表列表。事实上,每次添加都会创建一个新的列表。相反,您希望使用遍历所有列表并将项附加到新列表的解决方案。你知道吗

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

或者使用itertools。你知道吗

from itertools import chain

new_list = list(chain(*lists))

sum操作一系列元素,例如sum([1, 2, 3])(产生6)或sum([ [1], [2] ], [])(产生[1, 2])。第二个参数是可选的,start值。例如,sum([1, 2, 3], 10)将从10开始求和,提供16start默认为0:如果对非数字对象求和,则必须提供兼容的start值。你知道吗

当你给它sum(a, b)时,列表a就变成了参数列表。sum所做的是(正确地)遍历该列表的项,将它们添加到您提供的start值中。逻辑是这样的:

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

因此,您要做的第一件事就是result = [2] + 1。记住,第一个参数是你想加起来的东西的序列。让您的尝试奏效的最微不足道的变化(尽管不是最可读的)是

sum([a], b)

它产生[2, 1],因为b是起始值。你知道吗

这能解释发生了什么吗?你知道吗

相关问题 更多 >

    热门问题