Python在函数之间传递数组
找不到最近几年写的任何解决方案 我希望将变量从一个函数传递到另一个函数,而无需重新运行SQL连接 第一个功能是:Python在函数之间传递数组,python,pandas,Python,Pandas,找不到最近几年写的任何解决方案 我希望将变量从一个函数传递到另一个函数,而无需重新运行SQL连接 第一个功能是: def SQL_Country(): conn = psq.connect("localhost","root","root","world",cursorclass=psq.cursors.DictCursor) query = "SELECT * FROM country" with conn: cursor = conn.cursor(
def SQL_Country():
conn = psq.connect("localhost","root","root","world",cursorclass=psq.cursors.DictCursor)
query = "SELECT * FROM country"
with conn:
cursor = conn.cursor()
cursor.execute(query)
country = cursor.fetchall()
global df
df = pd.DataFrame(country, columns=["Code", "Name", "Continent", "Population", "HeadOfState"])
第二个函数,我希望传递SQL\u Country()
的输出:
def assignment():
## do something here
elif Choice == 6:
try:
x = df
except NameError:
x = None
if x is None:
print()
df = SQL_Country(df)
我得到以下错误:
File "Python.py", line 185, in assignment
df = SQL_Country(df)
UnboundLocalError: local variable 'df' referenced before assignment
关于如何将输出从一个函数传递到另一个函数的任何建议?第二个函数缺少参数:
def assignment(df):
您应该在SQL_County内返回df,而不是全局:
global df
df = pd.DataFrame(country, columns=["Code", "Name", "Continent", "Population", "HeadOfState"])
应该是:
return pd.DataFrame(country, columns=["Code", "Name", "Continent", "Population", "HeadOfState"])
然后使用:
df = SQL_Country()
如果要缓存df的结果,我将使用lru_缓存:
import functools
@functools.lru_cache(maxsize=1)
def SQL_Country():
...
这样,数据库获取只执行一次
我想你应该 您正在使用定义函数
def SQL_Country():
但是,当您使用函数时,您在以下位置提供了一个参数(不应作为函数输入):
此外,您的功能:
def assignment():
可能还应该输入一个数据帧,使其看起来像:
def assignment(df):
此时,对函数的后续调用将是:
assignment(df)
而不是
assignment()
由于已设置了
df
,因此无需再次运行SQL\u Country()
函数。所以我会检查一下它是否已经设置好了,如果已经设置好了,就返回它。首先在函数外部定义df,而不是使用全局值
df_country = None
def SQL_Country():
if df_country is None:
conn = psq.connect("localhost","root","root","world",cursorclass=psq.cursors.DictCursor)
query = "SELECT * FROM country"
with conn:
cursor = conn.cursor()
cursor.execute(query)
country = cursor.fetchall()
df_country = pd.DataFrame(country, columns=["Code", "Name", "Continent", "Population", "HeadOfState"])
return df_country
现在,当您调用该函数时,它不会在第二次执行它,但您会得到您所寻找的值
def assignment():
## do something here
if Choice == 6:
# No need to do the name check
x = SQL_Country()
if x is None:
print()
这有点令人困惑。当函数
SQL\u Country
不接受任何参数时,为什么要调用SQL\u Country(df)
?停止使用global
,您需要从第一个函数返回df,并将其作为参数输入到第二个函数。为什么不从SQL_Country()返回df?在python中,如何在函数之间传递数据从未改变过。为什么解决方案有多旧很重要?虽然您将df定义为全局的,但在调用函数之前,它不会被激活。
df_country = None
def SQL_Country():
if df_country is None:
conn = psq.connect("localhost","root","root","world",cursorclass=psq.cursors.DictCursor)
query = "SELECT * FROM country"
with conn:
cursor = conn.cursor()
cursor.execute(query)
country = cursor.fetchall()
df_country = pd.DataFrame(country, columns=["Code", "Name", "Continent", "Population", "HeadOfState"])
return df_country
def assignment():
## do something here
if Choice == 6:
# No need to do the name check
x = SQL_Country()
if x is None:
print()