如何在不使用全局变量的情况下将列表从一个函数传递到另一个函数?

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 到其他函数吗? (我还有一些函数需要处理数据)。

是的,直接作为参数传进去,return原来生成的时候

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 函数可以 return 一个可以在 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")

全局变量只有在你使用全局这个词时才能设置

您无需任何特殊操作即可访问全局变量

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