我正在尝试将一个txt
文件添加到Python中的列表中,然后遍历列表查找数字并将它们全部添加到一起。
示例文字:
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()
答案 0 :(得分:3)
您需要将作为字符串提供的填充转换为数字。要执行此操作,请更改以下行:
total_pop = total_pop + i.isdigit()
阅读:
total_pop = total_pop + int(i)
答案 1 :(得分: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
答案 2 :(得分:-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
要使用的词典会更好