【问题标题】:Python3.5 How to convert list of strings to int so I can sum up the total?Python3.5 如何将字符串列表转换为int,以便总结总数?
【发布时间】:2016-03-16 16:08:52
【问题描述】:
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

【问题讨论】:

  • 寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定问题或错误在问题本身中重现它所需的最短代码。没有明确的问题陈述的问题对其他读者没有用处。请参阅:How to create a Minimal, Complete, and Verifiable Example

标签: string list int python-3.5


【解决方案1】:

如果您只想获取所有数字并将它们相加,则如果您删除星号并正确缩进,您的代码就可以工作。缩进在 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-14
    • 2012-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-24
    相关资源
    最近更新 更多