将浮点数转换为 python 中的总和
converting float to sum in python
fname = input("Enter file name: ")
count=0
fh = open(fname)
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") : continue
count=count+1
halo=line.find("0")
gh=line[halo:]
tg=gh.rstrip()
ha=float(tg)
total=0
for value in range(ha):
total=total+value
print total
它就像文件中的十进制数列表 ok
0.1235
0.1236
0.1678
我将其转换为浮点数,其中 'tg' 没有像列表那样的数组
ha=float(tg)
total=0
for value in range(ha):
total=total+value
print total
错误:开头必须是整数
我知道使用范围是错误的,我应该使用什么来代替范围?
如果你想得到浮点数的总和,只需使用代码:
fname = input("Enter file name: ")
count = 0
total = 0
fh = open(fname)
for line in fh:
if not line.startswith("X-DSPAM-Confidence:"): continue
count += 1
halo = line.find("0")
gh = line[halo:]
tg = gh.rstrip()
ha = float(tg)
total += ha
print total
您将浮点数作为参数传递给 range
,这没有意义。 range
returns 一个包含 n 个元素的列表,当 n 是范围的唯一参数时。例如:
>>> range(3)
[0, 1, 2]
所以你可以看到浮点数的范围没有意义。
如果我正确理解你的代码,我认为你想要替换:
for value in range(ha):
total=total+value
由
total += ha
另外,尽量不要太迂腐,我对您的代码违反了多少 PEP 8 原则印象深刻。你可能觉得这没什么大不了的,但如果你在乎,我建议你读一读(https://www.python.org/dev/peps/pep-0008/)
fname = input("Enter file name: ")
count=0
fh = open(fname)
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") : continue
count=count+1
halo=line.find("0")
gh=line[halo:]
tg=gh.rstrip()
ha=float(tg)
total=0
for value in range(ha):
total=total+value
print total
它就像文件中的十进制数列表 ok
0.1235
0.1236
0.1678
我将其转换为浮点数,其中 'tg' 没有像列表那样的数组
ha=float(tg)
total=0
for value in range(ha):
total=total+value
print total
错误:开头必须是整数
我知道使用范围是错误的,我应该使用什么来代替范围?
如果你想得到浮点数的总和,只需使用代码:
fname = input("Enter file name: ")
count = 0
total = 0
fh = open(fname)
for line in fh:
if not line.startswith("X-DSPAM-Confidence:"): continue
count += 1
halo = line.find("0")
gh = line[halo:]
tg = gh.rstrip()
ha = float(tg)
total += ha
print total
您将浮点数作为参数传递给 range
,这没有意义。 range
returns 一个包含 n 个元素的列表,当 n 是范围的唯一参数时。例如:
>>> range(3)
[0, 1, 2]
所以你可以看到浮点数的范围没有意义。
如果我正确理解你的代码,我认为你想要替换:
for value in range(ha):
total=total+value
由
total += ha
另外,尽量不要太迂腐,我对您的代码违反了多少 PEP 8 原则印象深刻。你可能觉得这没什么大不了的,但如果你在乎,我建议你读一读(https://www.python.org/dev/peps/pep-0008/)