[英]Using python sessions to pass variable from one function to another function
[英]How to pass list from one function to another without using global variable?
我对 python 很陌生,目前正在尝试一个项目,该项目要求用户从 csv 文件中读取数据,并存储该数据以便可以对其执行其他功能。 我目前似乎遇到的唯一问题是我不能使用全局变量。
刚才我有以下代码结构:
import csv
import sys
data_set = []
def loadFile(x):
with open(x, "r") as readfile:
csv_reader = csv.reader(readfile, delimiter= ';')
for row in csv_reader:
data_set.append(row)
print("Loaded weather data from", (x[0:-4]).capitalize())
print()
def avgDay(x):
for line in data_set:
if(len(x) == 5 and (x[3:5] + "-" + x[0:2]) in line[0]):
print("The weather on", x, "was on average", line[2], "centigrade")
有什么方法可以将 data_set 调用到其他函数吗? (我还有一些需要处理数据的函数)。
是的,只需将其作为参数传入,并在最初生成时返回。
import csv
import sys
def loadFile(x):
date_set = []
with open(x, "r") as readfile:
csv_reader = csv.reader(readfile, delimiter= ';')
for row in csv_reader:
data_set.append(row)
print("Loaded weather data from", (x[0:-4]).capitalize())
print()
return data_set
def avgDay(x, data_set):
for line in data_set:
if(len(x) == 5 and (x[3:5] + "-" + x[0:2]) in line[0]):
print("The weather on", x, "was on average", line[2], "centigrade")
def main():
data_set = loadFile(...)
avgDay(..., data_set)
if __name__ == 'main':
main()
您的 loadFile function 可以返回可以在 avgDay 中使用的数据集
import csv
import sys
def loadFile(x):
data_set = []
with open(x, "r") as readfile:
csv_reader = csv.reader(readfile, delimiter= ';')
for row in csv_reader:
data_set.append(row)
print("Loaded weather data from", (x[0:-4]).capitalize())
print()
return data_set
def avgDay(x):
data_set = loadFile(x)
for line in data_set:
if(len(x) == 5 and (x[3:5] + "-" + x[0:2]) in line[0]):
print("The weather on", x, "was on average", line[2], "centigrade")
仅当您使用 global 一词时才能设置 global vars
您可以访问全局变量而无需任何特殊
data_set = "global_var" #global
def print_global_data_set():
print(data_set)
def set_global_data_set():
global data_set # you need this line to tell python that you are going to set a global variable
data_set = 'global_var_set_from_function'
def set_local_data_set():
data_set = "local" # this will not set the global var but a local var so the global data_set stays unchanged
print(data_set) # outputs "global_var"
set_local_data_set()
print_global_data_set() # outputs "global_var" (set_local_data_set did not set the global var but a local var)
set_global_data_set()
print_global_data_set() # outputs "global_var_set_from_function"
函数可以有属性。 您可以将 data_set 设为 loadFile 的一个属性,然后在 avgDay 中引用它。
with open(x, "r") as readfile:
csv_reader = csv.reader(readfile, delimiter= ';')
for row in csv_reader:
data_set.append(row)
loadFile.data_set_attr = data_set
然后,在 avgDay 中,引用 loadFile.data_set_attr
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.