gpt4 book ai didi

python - 如何在python中定义全局数组

转载 作者:行者123 更新时间:2023-12-03 23:24:05 35 4
gpt4 key购买 nike

如何在python中定义全局数组
我想将 tm 和 prs 定义为全局数组,并在两个函数中使用它们,我该如何定义它们?

import numpy as np 
import matplotlib.pyplot as plt

tm = []
prs = []

def drw_prs_tm(msg):
tm = np.append(tm,t)
prs = np.append(prs,s)

def print_end(msg):
plt.plot(tm,prs,'k-')

最佳答案

您需要将它们称为 global <var_name>在方法中

def drw_prs_tm(msg):
global tm
global prs

tm = np.append(tm,t)
prs = np.append(prs,s)

def print_end(msg):
global tm
global prs
plt.plot(tm,prs,'k-')

阅读更多 global herehere

The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. It would be impossible to assign to a global variable without global, although free variables may refer to globals without being declared global.

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a new value anywhere within the function’s body, it’s assumed to be a local. If a variable is ever assigned a new value inside the function, the variable is implicitly local, and you need to explicitly declare it as ‘global’.

关于python - 如何在python中定义全局数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19139201/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com