2014-11-01 36 views
1

我想将一个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

没有你的文件有两个新行? – Hackaholic 2014-11-01 22:19:38

+0

没有它的只是一个新的行,文本的状态名称没有空格后跟一个空格然后人口号 – Cos 2014-11-01 22:24:36

+0

我知道它是很长的阅读,但有一个伟大的Python教程在这里:https://docs.python.org/2/tutorial /和here:http://pymotw.com/2/contents.html – dnozay 2014-11-01 22:37:56

回答

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

o好点你喜欢使用散列表还是设置 – Cos 2014-11-01 22:27:02

+0

是的,就像散列表一样。 – dnozay 2014-11-01 22:28:14

+0

快速的问题,恐怕我想用set()。如何将文本文件中的每一行添加到集合中? – Cos 2014-11-01 22:55:33

3

您需要将提供的字符串转换为数字。要做到这一点改变行从:

total_pop = total_pop + i.isdigit() 

阅读:

total_pop = total_pop + int(i) 
-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 

字典使用会更好

+0

可以告诉我为什么downvoting?任何理由或我错了? – Hackaholic 2014-11-01 22:31:26

+0

啊,这是一个输入错误 – Hackaholic 2014-11-01 22:35:12