![](/img/trans.png)
[英]How to reference not-yet-declared functions in a global variable in 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])
您必須將結果移到函數之外。 我認為沒有其他方法可以將變量移出。
一種方法是將結果作為參數傳遞給乘法方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.