Python3.5如何将字符串列表转换为int所以我可以总结一下?

时间:2015-12-10 21:10:43

标签: string list int python-3.5

import re
numlist = list()
*total = 0*
handle = open('test.txt')
for line in handle:
    line = line.rstrip()
    x = re.findall('([0-9]+)', line)
    if len(x) > 0:
    *for nums in x:
        numlist.append(nums)
        value = int(nums)
        total = total+value

打印(总)*

test.txt文件的示例:

jhjkhjhhjkhjh 5678 kjhlkjsd lkjaksd 6578 8765 hnhdtriusnfasdasdweefgdf dfdf dfdfdfdferse5667 9876gjshdi ksdhsks k6453jjhkkk 9087jjskldnjck kjshhdck 9877 khhgjnh 8532 jnhyg 7634iutr jhgpiunegjd wert 1234 kjhg 4567 kjh b 0987 jhggebndueh nhergsus df 9987 7654 0129kk jhikhhhgkjhhjiiksyehf 9876 ijh kjhgj 1234

1 个答案:

答案 0 :(得分:0)

如果您只想获取所有数字并将它们相加,那么如果删除星号并正确缩进,则代码可以正常工作。缩进在python中至关重要。不知道为什么星号在那里?

import re

numlist = list()
total = 0
handle = open('test.txt')
for line in handle:
    line = line.rstrip()
    x = re.findall('([0-9]+)', line)
    if len(x) > 0:
        for nums in x:
            numlist.append(nums)
            value = int(nums)
            total = total+value
print(total)

我会稍微更改一下,你没有提到你想要使用numlist的内容,所以我在下面的代码中删除了它。

import re

total = 0
with open('test.txt') as handle:
    for line in handle:
        x = re.findall('([0-9]+)', line)
        for num in x:
            total += int(num)
print(total)