Python 如何在嵌套函数中正确引用全局变量
How to properly reference a global variable in nested functions in Python
假设我有以下简单情况:
import pandas as pd
def multiply(row):
global results
results.append(row[0] * row[1])
def main():
results = []
df = pd.DataFrame([{'a': 1, 'b': 2}, {'a': 3, 'b': 4}, {'a': 5, 'b': 6}])
df.apply(multiply, axis=1)
print(results)
if __name__ == '__main__':
main()
这导致以下回溯:
Traceback (most recent call last):
File "<ipython-input-2-58ca95c5b364>", line 1, in <module>
main()
File "<ipython-input-1-9bb1bda9e141>", line 11, in main
df.apply(multiply, axis=1)
File "C:\Users\bbritten\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\frame.py", line 4262, in apply
ignore_failures=ignore_failures)
File "C:\Users\bbritten\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\frame.py", line 4358, in _apply_standard
results[i] = func(v)
File "<ipython-input-1-9bb1bda9e141>", line 5, in multiply
results.append(row[0] * row[1])
NameError: ("name 'results' is not defined", 'occurred at index 0')
我知道我可以将 results = []
移动到 if
语句来使这个示例工作,但是有没有办法保持我现在的结构并使其工作?
您必须在函数外声明结果,例如:
import pandas as pd
results = []
def multiply(row):
# the rest of your code...
更新
另请注意,python 中的 list
是可变的,因此您无需在函数开头使用 global 指定它。例子
def multiply(row):
# global results -> This is not necessary!
results.append(row[0] * row[1])
您必须将结果移出函数。我认为没有任何其他方法可以不将变量移出。
一种方法是将结果作为参数传递给 multiply 方法。
假设我有以下简单情况:
import pandas as pd
def multiply(row):
global results
results.append(row[0] * row[1])
def main():
results = []
df = pd.DataFrame([{'a': 1, 'b': 2}, {'a': 3, 'b': 4}, {'a': 5, 'b': 6}])
df.apply(multiply, axis=1)
print(results)
if __name__ == '__main__':
main()
这导致以下回溯:
Traceback (most recent call last):
File "<ipython-input-2-58ca95c5b364>", line 1, in <module>
main()
File "<ipython-input-1-9bb1bda9e141>", line 11, in main
df.apply(multiply, axis=1)
File "C:\Users\bbritten\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\frame.py", line 4262, in apply
ignore_failures=ignore_failures)
File "C:\Users\bbritten\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\frame.py", line 4358, in _apply_standard
results[i] = func(v)
File "<ipython-input-1-9bb1bda9e141>", line 5, in multiply
results.append(row[0] * row[1])
NameError: ("name 'results' is not defined", 'occurred at index 0')
我知道我可以将 results = []
移动到 if
语句来使这个示例工作,但是有没有办法保持我现在的结构并使其工作?
您必须在函数外声明结果,例如:
import pandas as pd
results = []
def multiply(row):
# the rest of your code...
更新
另请注意,python 中的 list
是可变的,因此您无需在函数开头使用 global 指定它。例子
def multiply(row):
# global results -> This is not necessary!
results.append(row[0] * row[1])
您必须将结果移出函数。我认为没有任何其他方法可以不将变量移出。
一种方法是将结果作为参数传递给 multiply 方法。