user2933041
user2933041

Reputation: 31

sum up objects of a list

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

Answers (3)

Javier Castellanos
Javier Castellanos

Reputation: 9874

print sum([float(x.strip()) for x in open(filename)])  

Upvotes: 1

Totem
Totem

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

thefourtheye
thefourtheye

Reputation: 239443

  1. Instead of

    Lists = line
    

    you need

    Lists.append(line)
    
  2. You can get the total sum like this

    total = sum(sum(map(int, item)) for item in Lists)
    
  3. If you dont want to create list of lists, you can use extend function

    Lists.extend(line)
    ...
    total = sum(map(int, Lists))
    

Upvotes: 5

Related Questions