user6263406 user6263406 - 7 months ago 8
Python Question

List understanding python

I'm pretty confused i'm supposed to take a file that the user inputs and take the scores in the text document and turn it into a list.

the problem I'm having is that when i turn it into a list it gives me three separate list under one variable.

def main():
file = input("Enter a filename: ")
file1 = open(file, "r")
Scores = (file1.readlines())
for line in Scores:
scores = [eval(i) for i in line.split()]

print(scores)


and i get this as an output:

[34, 34, 54, 14, 32, 24, 31, 34, 53, 74, 22, 29]
[54, 34, 14, 14, 32, 24, 31, 34, 53, 74, 22, 29]
[66, 53, 19, 45, 39, 72, 51, 46, 64, 33, 44, 55]


could i please get help turning this into one whole list so i can display how many scores there are, the total of all of them, and the average.

Answer

This will do what you want:

def main():
    file = input("Enter a filename: ")
    file1 = open(file, "r")
    Scores = (file1.readlines())
    scores_list = []
    for line in Scores:
        scores_list.extend([eval(i) for i in line.split()])

    print(scores_list)

The trick is to extend an existing list with your new list for each line in the file.

Note that there are other opportunities for improvements here... e.g. you could use a context manager to manage closing the file properly:

 def main():
    filename = input("Enter a filename: ")
    scores_list = []
    with open(filename, "r") as file1:
        for line in file1:
            scores_list.extend([eval(i) for i in line.split()])

    print(scores_list)

Finally (and probably most importantly), you can probably just swap out your use of eval for int or float (depending on the inputs) and make your program much more secure. As it is, eval will run any untrusted code on your machine. To demonstrate, add a line with exit() into your text file and notice that your program exits before it does anything. An attacker could use this to do malicious things (like wipe your home-directory or even your entire drive if the script runs with high enough permissions).

Comments