Reading Multiple Lists Using SUM function - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Reading Multiple Lists Using SUM function (/thread-27314.html) |
Reading Multiple Lists Using SUM function - dgrunwal - Jun-02-2020 Hello, Here is the code I am trying to improve - can longer lists be read from a file and looped through and printed? p8262 = [331, 83, 112, 111, 21, 67, 8] p8264 = [384, 84, 119, 74, 28, 51, 6] p8401 = [330, 114, 217, 81, 11, 52, 5] # variables to be looped Sum = sum(p8262) Sum1 = sum(p8264) Sum2 = sum(p8401) print("The sum of p8262 is " , Sum) print("The sum of p8264 is " , Sum1) print("The sum of p8401 is " , Sum2) All the Best, Dave RE: Reading Multiple Lists Using SUM function - Larz60+ - Jun-03-2020 you can do all in one like: print(f"The sum of p8262 is {sum(p8262)}")
RE: Reading Multiple Lists Using SUM function - dgrunwal - Jun-03-2020 Thanks! That works. Is there a way to read and loop through a file? Have around 300 lists. RE: Reading Multiple Lists Using SUM function - buran - Jun-03-2020 what is the file - json? show what you have RE: Reading Multiple Lists Using SUM function - dgrunwal - Jun-03-2020 It's a text file with 259 identical lists like so. p8262 = [331, 83, 112, 111, 21, 67, 8] p8264 = [384, 84, 119, 74, 28, 51, 6] p8401 = [330, 114, 217, 81, 11, 52, 5] ... print(f"The sum of p8262 is {sum(p8262)}") Can just the name of the lists be assigned as a variable then I could print out the list name and sum return. Best RE: Reading Multiple Lists Using SUM function - buran - Jun-03-2020 this is weird file format. you can do something like from ast import literal_eval with open(path_to_your_file) as f: for line in f: name, values = line.split(' = ') values = literal_eval(values) print(f"The sum of {name} is {sum(values)}")of course, instead of ast.literal_eval, you can parse the list yourself, i.e. after the split at =, you can remove the brackets, split at comma, convert numbers to int, and so on... RE: Reading Multiple Lists Using SUM function - dgrunwal - Jun-03-2020 Bingo buran - thanks all, BTW this is the coolest python forum. :) |