Home > other >  Sum a list of numbers in string representation with leading whitespace
Sum a list of numbers in string representation with leading whitespace

Time:03-21

I made a for loop to collect a list from a file by its index. The file's first line is a name, then numbers following by its lines.

with open(ff, "r") as file:
    while line := file.readline():
     AtBats.append(line.split(",")[-1])

AtBats = AtBats[1:]



print(AtBats)
rep = []
for x in AtBats:
    rep.append(x.replace('\n',''))
print(rep)

I get a list like this. How can I sum all of the numbers in this list?

[' 2', ' 6', ' 3', ' 5', ' 2']

CodePudding user response:

You can transform each string in the list to an integer using int():

data = [' 2', ' 6', ' 3', ' 5', ' 2']
result = sum(int(item) for item in data)
print(result)

This prints:

18

CodePudding user response:

You could convert the strings to numbers already while reading the file, then just use sum on the list:

AtBats = []
with open(ff, "r") as file:
    next(file)
    while line := file.readline():
        AtBats.append(int(line.split(",")[-1]))

print(AtBats)
print(sum(AtBats))

Output:

[2, 6, 3, 5, 2]
18
  • Related