Cos
Cos

Reputation: 129

Iterating through a list to add values

I am trying to add a txt file to a list in Python, then iterate through the list finding the numbers and adding them all together.

sample text:

Alabama 4780
Alaska 710
Arizona 6392
Arkansas 2916
California 37254
Colorado 5029

expected output:

['Alabama', '4780', 'Alaska', '710', 'Arizona', '6392', 'Arkansas', '2916', 'California', '37254', 'Colorado', '5029']

total population: 57621

I can add them to the list just fine but am unable to find the total of all the numbers. Ideally I'd like to have it all in one function.

def totalpoplst(filename):
    lst = []
    with open(filename) as f:
        for line in f:
            lst += line.strip().split(' ')
        return print(lst)
    totalpop()

def totalpop(filename):
    total_pop = 0
    for i in lst:
        if  i.isdigit():
            total_pop = total_pop + i.isdigit()
    return print(total_pop)

def main():
    filename = input("Please enter the file's name: ")
    totalpoplst(filename)

main()

Upvotes: 1

Views: 1701

Answers (3)

dnozay
dnozay

Reputation: 24344

It is better to use dict for key-value data structures than a list.

>>> population = {}
>>> total = 0
>>> with open('list.txt', 'r') as handle:
...     for line in handle:
...         state, sep, pop = line.partition(' ')
...         population[state] = int(pop)
...         total += population[state]
... 
>>> total
57081

Upvotes: 1

Hackaholic
Hackaholic

Reputation: 19763

f = open('your_file.txt')  
your_dict={}
total_pop = 0
for x in f:
    x=x.strip()
    s,p=x.split(' ')
    your_dict[s]=p
    total_pop +=int(p)
print your_dict
print total_pop

Dictionary to use will be better

Upvotes: -1

Maria Zverina
Maria Zverina

Reputation: 11173

You need to convert the population supplied as a string to a number. To do this change the line from:

total_pop = total_pop + i.isdigit()

to read:

total_pop = total_pop + int(i)

Upvotes: 3

Related Questions