SyntaxError trying to return 赋值的值
SyntaxError trying to return the value of assignment
假设我有一个带有列表参数的函数,并且我想在它的主体中修改传递的列表,代码如下:
spy = [0,0,7]
def replace_spy(lista):
return lista[2]=lista[2]+1
但它告诉我错误:SyntaxError: invalid syntax
赋值是语句,不是表达式。它没有价值。所以你不能return
赋值的值。
在 允许这种事情的语言中,return 值到底应该是什么是模棱两可的,但是大多数语言——包括 C 和许多语言派生自 C 或受其启发 - 将为您提供 lista[2]
1 的新值。所以大概你想要这个:
def replace_spy(lista):
lista[2]=lista[2]+1
return lista[2]
如果您希望缩短内容,可以减少击键次数,而且可能更具可读性:
def replace_spy(lista):
lista[2] += 1
return lista[2]
1.作为 "lvalue",但这在 Python 中没有意义。
假设我有一个带有列表参数的函数,并且我想在它的主体中修改传递的列表,代码如下:
spy = [0,0,7]
def replace_spy(lista):
return lista[2]=lista[2]+1
但它告诉我错误:SyntaxError: invalid syntax
赋值是语句,不是表达式。它没有价值。所以你不能return
赋值的值。
在 允许这种事情的语言中,return 值到底应该是什么是模棱两可的,但是大多数语言——包括 C 和许多语言派生自 C 或受其启发 - 将为您提供 lista[2]
1 的新值。所以大概你想要这个:
def replace_spy(lista):
lista[2]=lista[2]+1
return lista[2]
如果您希望缩短内容,可以减少击键次数,而且可能更具可读性:
def replace_spy(lista):
lista[2] += 1
return lista[2]
1.作为 "lvalue",但这在 Python 中没有意义。