试图从一个子例程到另一个子例程获取列表

时间:2016-11-30 18:01:40

标签: python list global-variables subroutine

我正在从文件中的数据创建一个列表,我不能使用它的原始子程序列表,我怎么能让它全局,所以我可以使用它并在任何我想要的地方改变它?

def selecting_qs():
    global main_list
    dif = difficulty.get()
    print(main_list,dif)


#main list order:
#Question ID  ,  Difficulty  ,  Topic  ,  Answer ID  ,  Picture ID  ,  Frequency 
def main_file_info():
    main_file = open("main_file.txt","r")
    main_file_info=main_file.readlines()
    for line in main_file_info:
        main_list=line.split("@")

    main_list=main_list[1:len(main_list)-1]
    main_file.close()

    return(main_list)

1 个答案:

答案 0 :(得分:1)

要传递函数中使用的变量,您只需返回它们,指定它们以及传递它们。在您当前的脚本中,这将如下所示:

def selecting_qs(a_list):
    # global  <-- main_list this is not needed and can lead to problems!
    dif = difficulty.get()
    print(a_list, dif)


#main list order:
#Question ID  ,  Difficulty  ,  Topic  ,  Answer ID  ,  Picture ID  ,  Frequency 
def main_file_info():
    main_file = open("main_file.txt","r")
    main_file_info=main_file.readlines()
    for line in main_file_info:
        main_list=line.split("@")

    main_list=main_list[1:len(main_list)-1]
    main_file.close()

    return main_list  # returning the item(s) thus making them accessible from the outer scope

my_main_list = main_file_info()  # assigning the item(s) to a variable
selecting_qs(my_main_list)  # passing the item(s) to another function

如果有疑问,请告诉我。