【问题标题】:Read file and sum integer读取文件并求和整数
【发布时间】:2015-03-24 00:51:59
【问题描述】:

我是 python 新手,我试图读取我的文件并抓取整数并将它们放入一个列表中,最后得到它们的总和。

这是文件:

12  234 23  23  3921 4 523 2212 23
212  234 23  23  39
21 4 523 22192 23 2

这是我已经走了多远,尝试打印值并将空格删除到列表中:

reader = open('sumAllExample.txt','r')
data = reader.read()
reader.close()
reader = str.split(data)
print reader

我不明白为什么它会拆分一些整数:

['12', '234', '23', '23', '392', '1', '4', '523', '2', '2', '19', '2', '23', '2', '12', '234', '23', '23', '39', '2', '1', '4', '523', '2', '2', '19', '2', '23', '2']

这里:

'1'
'2'
' '
' '
'2'
'3'
'4'
' '
'2'
'3'
' '
' '
'2'
'3'
' '
' '
'3'
'9'
'2'
'\n'
'1'
' '
'4'
' '
'5'
'2'
'3'
' '
'2'
'\n'
'2'
'\n'
'1'
'9'
'\n'
'2'
' '
'2'
'3'
'\n'
'2'
'\n'
'1'
'2'
' '
' '
'2'
'3'
'4'
' '
'2'
'3'
' '
' '
'2'
'3'
' '
' '
'3'
'9'
'\n'
'2'
'\n'
'1'
' '
'4'
' '
'5'
'2'
'3'
' '
'2'
'\n'
'2'
'\n'
'1'
'9'
'\n'
'2'
' '
'2'
'3'
' '
'2'
'\n'

【问题讨论】:

  • 您的代码看起来没问题(除了重复使用名称 reader 令人困惑,以及过于冗长的 str.split(data) 而不是 data.split())。我怀疑问题出在输入文件中。我建议您对其进行 hexdump 以确保它确实包含您认为的内容。
  • 遍历文件对象for line in data: print(repr(line))
  • @jamylak, '2', '2', '19', '2' 没有意义
  • 好的,你需要做一个data = reader.read().replace("\n","").split()。你的数字之间有换行符
  • 可能有很多原因,具体取决于数据的原始来源。无论如何,总是使用repr 如果你得到的输出你似乎没有得到你所期望的。

标签: python list integer sum


【解决方案1】:
with open("filename") as f:
    rd=f.readlines()
    for x in rd:
        q=x.replace("\n","").split()
        print (sum(int(t) for t in q))

这个有效。对于replace()\n 部分检查@ Padraic Cunningham 的cmets。如果你以前使用with open() 方法进行文件处理会更好。

【讨论】:

    猜你喜欢
    • 2012-08-06
    • 1970-01-01
    • 1970-01-01
    • 2018-07-22
    • 1970-01-01
    • 2021-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多