遍历列表以添加值

1 投票
3 回答
1697 浏览
提问于 2025-05-01 01:58

我正在尝试在Python中把一个txt文件的内容添加到一个列表里,然后遍历这个列表,找出所有的数字并把它们加在一起。

示例文本:

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

预期输出:

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

total population: 57621

我可以把数字添加到列表里,但就是无法计算出所有数字的总和。理想情况下,我希望能把这些操作都放在一个函数里。

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()
暂无标签

3 个回答

-1
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

使用字典会更好

3

你需要把提供的人口数据从字符串形式转换成数字。要做到这一点,把这一行代码改成:

total_pop = total_pop + i.isdigit()

改成:

total_pop = total_pop + int(i)
1

dict 来存储键值对的数据比用列表要好。

>>> 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

撰写回答