我试图读取一个文件,然后找到所有数值的总和。我一直在第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)
这几乎就是纳尔的答案:
…不同之处在于try/except稍微简单一点,而且在求和之前它不会建立一个(潜在的巨大的)数字列表。你知道吗
假设您的输入文件onle每行有一个简单的字符串。这将评估行是否可以转换为float,然后将该float附加到列表中。你知道吗
使用regexp:
如果需要所有数值的列表:
相关问题 更多 >
编程相关推荐