Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/unity3d/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在赋值错误之前理解引用_Python_List Comprehension - Fatal编程技术网

Python 在赋值错误之前理解引用

Python 在赋值错误之前理解引用,python,list-comprehension,Python,List Comprehension,下面的代码 def is_leaf(tree): return type(tree) != list def count_leaf(tree): if is_leaf(tree): return 1 branch_counts = [count_leaf(b) for b in tree] return sum(branch_counts) def is_leaf(tree): return type(tree) != list de

下面的代码

def is_leaf(tree):
    return type(tree) != list

def count_leaf(tree):
    if is_leaf(tree):
        return 1
    branch_counts = [count_leaf(b) for b in tree]
    return sum(branch_counts)
def is_leaf(tree):
    return type(tree) != list

def count_leaf(tree):
    if is_leaf(tree):
        return 1
    for b in tree:
        branch_counts = [count_leaf(b)]
    return sum(branch_counts)
在表达式
sum(branch\u counts)
中引用
branch\u counts
时不会引发此类错误

但在代码下面

def is_leaf(tree):
    return type(tree) != list

def count_leaf(tree):
    if is_leaf(tree):
        return 1
    branch_counts = [count_leaf(b) for b in tree]
    return sum(branch_counts)
def is_leaf(tree):
    return type(tree) != list

def count_leaf(tree):
    if is_leaf(tree):
        return 1
    for b in tree:
        branch_counts = [count_leaf(b)]
    return sum(branch_counts)
在表达式
sum(branch\u counts)
中引用
branch\u counts
时是否引发此类错误


在第一种情况下,
分支计数
尚未通过计算列表理解表达式进行计算,为什么在第一种情况下不会抛出错误?

如果树为空,
[]
,则
分支计数
变量未初始化

要使代码与第一个代码等效,请对其进行如下修改:

def count_leaf(tree):
    if is_leaf(tree):
        return 1
    branch_counts = list()
    for b in tree:
        branch_counts.append(count_leaf(b))
    return sum(branch_counts)

请注意。。第一个和第二个代码是不同的,如果您想让它做相同的工作,那么在第二个代码中将行更改为

branch_counts.append(count_leaf(b))

在这种情况下不会打印任何内容,因为
s

a=[]
for s in a:
   print "hi"
同样地,{},()

因此,第二种情况是,如果
tree
为空,则不会创建变量

i、 e.)

程序中的一个错误是:

branch_counts = [count_leaf(b)]
始终只创建一个元素的列表

它必须在循环中的某些地方启动,如
分支计数=[]

然后在循环中:

branch_counts.append(count_leaf(b))

在第一个示例中,由于使用列表理解,
branch\u counts
使用空列表进行初始化:

>>> branch_counts = [count_leaf(b) for b in []]]
[]
在第二个示例中,for循环没有运行,因为
树中没有
b
。因此,
branch\u counts
从未分配任何内容

>>> for b in []:
>>>     branch_counts = [count_leaf(b)]
>>> sum(branch_counts)
NameError: name 'branch_counts' is not defined

除此之外,正如其他人指出的,在第二个示例中,每次循环运行时都会新分配分支计数(而不是添加带有
append()
的内容)。

因此,您的意思是,在第一种情况下,
分支计数在任何情况下都会被初始化。因此,python解释器理解这一点,并且在第一种情况下没有错误。我说的对吗?对。但列表理解可能返回一个空列表<在这种情况下,code>sum
将返回一个
0
。另一个+1用于更好的替代解决方案。除了我的第一个案例纯粹是功能性的(无状态的)。您的解决方案正在改变状态。