只需要从文件中读取数值,然后求和

2024-10-02 22:29:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图读取一个文件,然后找到所有数值的总和。我一直在第19行得到一个不支持的类型错误,当我试图打印列表时,我得到一个非常奇怪的输出。文件在下面,我只需要读取数值。你知道吗

文件

q

w

e

r

t

y

u

i

o

p

1

2

3

4

5

6

7

8

9

0

[

]

,

.

/

0.9

9.8

8.7

7.6

6.5

5.4

4.3

3.2

2.1

1.0

def sumOfInt():

with open("sample.txt", "r") as infile:
    list = [map(float, line.split()) for line in infile]
    sumInt = sum(list)

print("The sum of the list isi:", sumInt)

Tags: 文件类型列表def错误withlineopen
3条回答

这几乎就是纳尔的答案:

def sumOfInt():
    with open("sample.txt", "r") as infile:
        total = 0
        for line in infile:
            try:
                total += float(line)
            except ValueError:
                pass

print("The sum of the list is:", total)

…不同之处在于try/except稍微简单一点,而且在求和之前它不会建立一个(潜在的巨大的)数字列表。你知道吗

def sumOfInt():

  with open("sample.txt", "r") as infile:
      floatlist = []
      for line in infile:
          try:
              floatlist.append(float(line))
          except:
              pass
      sumInt = sum(floatlist)

      print("The sum of the list isi:", sumInt)

假设您的输入文件onle每行有一个简单的字符串。这将评估行是否可以转换为float,然后将该float附加到列表中。你知道吗

使用regexp:

import re

with open("sample.txt", "r") as infile:
    total = sum(map(float, re.findall("\d+.\d+|\d+", inifile.read())))

如果需要所有数值的列表:

with open("sample.txt", "r") as infile:    
    values = re.findall("\d+.\d+|\d+", inifile.read())

相关问题 更多 >