我正在根据文件中的数据创建列表,但无法在其原始子例程之外使用该列表,我如何才能使其全局化,以便可以在任何需要的地方使用和更改它?

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)

最佳答案

要传递函数中使用的变量,您只需要返回它们,分配它们,然后传递它们即可。在您当前的脚本上,其外观如下:

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


如果有未解决的问题,请告诉我。

关于python - 试图从一个子例程到另一个子例程获取列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40895180/

10-11 12:19