函数Python外部列表为空

2024-06-05 23:28:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在一个函数中将文本文件的行复制到列表中,然后在第二个函数中打印该列表的内容。
如果我把print语句放在第一个函数中,它会输出正确的列表,但是如果我尝试用第二个函数打印,它会输出一个空列表。你知道吗

如何将列表从第一个函数传递到第二个函数?你知道吗

我的当前代码:

def selectfile():
    userselect = input("Please type the filename, for an example you can type: numbers.txt or 10lines.txt: ")
    file = open(userselect, "r") #  grabs the user input from above and opens the selected file
    return file # puts the value into selectfile func


def TxttoList():  # starts the paste function
    file = selectfile()  # grabs the info from the function above
    lines = file.readlines()[1:]  # starts loading in the content line by line
    newlist = []  # declares my list
    for line in lines:  # loops through each line
        content = line.strip().split("\t")  # uses tab as separator
        newlist.append(content)  # adds the lines to the list
 #  print(newlist) //Lists prints as expected here if i remove the #, but I need the list in the function below. 
    return newlist


def TopScore():  # This is where I need the list I created above
    newlist = TxttoList() 
    print(newlist)  

TxttoList()  # starts the program ```

我预期的结果是:

[Peter, 22] [hans, 11] [lars, 20] [flemming, 21] [dorte, 19] [bo, 11]

我得到的结果是:

非常感谢您的帮助。你知道吗


Tags: the函数列表deflinefunctionlistabove