Reputation: 31
i'm writing a code that should take in a filename and create an initial list. Then, i'm trying to sum up each item in the list. The code i've written so far looks something like this...
filename = input('Enter filename: ')
Lists = []
for line in open(filename):
line = line.strip().split()
Lists = line
print(Lists)
total = 0
for i in Lists:
total = sum(int(Lists[i]))
print(total)
I take in a filename and set all the objects in the line = to the List. Then, I make a variable total which should print out the total of each item in the list. For instance, if List = [1,2,3] then the total will be 6. However, is it possible to append integer objects to a list? The error i'm receiving is...
File "/Users/sps329/Desktop/testss copy 2.py", line 10, in main
total = sum(int(Lists[i]))
TypeError: list indices must be integers, not str
Something like this doesn't work also because the items in the List are strings and not numbers. Would I have to implement the function isdigit even though I know the input file will always be integers?...
total = sum(i)
Upvotes: 2
Views: 201
Reputation: 7349
# creates a list of the lines in the file and closes the file
with open(filename) as f:
Lists = f.readlines()
# just in case, perhaps not necessary
Lists = [i.strip() for i in Lists]
# convert all elements of Lists to ints
int_list = [int(i) for i in Lists]
# sum elements of Lists
total = sum(int_list)
Upvotes: 2
Reputation: 239443
Instead of
Lists = line
you need
Lists.append(line)
You can get the total sum like this
total = sum(sum(map(int, item)) for item in Lists)
If you dont want to create list of lists, you can use extend
function
Lists.extend(line)
...
total = sum(map(int, Lists))
Upvotes: 5