我有一份从文件中取出的数字清单。
fh = open(<filename>)
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") : continue
num = float(line[20 : ])
print(num)输出:
0.6178
0.6961000000000001
0.7565
0.7625999999999999
0.7556
0.7002
0.7615我必须将它们相加,然后取平均值(“我不能使用sum()")。我试着用'for‘遍历它们,然后用/操作符求和并得到平均值;但我得到了以下错误'float’object is not iterable。
我尝试了:
fh = open(<filename>)
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") : continue
num = float(line[20 : ])
for n in num:
n = n + n
print(n)有了这个,'float‘对象的错误是不可迭代的。
此外,我也尝试将数字添加到数组中,看看是否可以在数组中循环,但这对我也不起作用。
发布于 2021-01-04 22:26:15
您需要将总和累加到行上的for循环中的一个变量中。您还必须计算行数。你可以在你的代码中这样做:
fh = open(<filename>)
sum_num = 0 # Initialize the sum to 0
count = 0 # Initialize the counter of lines to 0
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") : continue
num = float(line[20 : ])
sum_num += num # Add your number to the sum
count += 1 # Add 1 to your counter of lines
print(num)
print(sum_num) # Print the sum
print(sum_num/count) # Print average which is just the sum divided by the number of lines发布于 2021-01-04 22:24:44
我认为你需要一个循环外的变量,例如:
fh = open(<filename>)
numbers = []
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") : continue
num = float(line[20 : ])
# save num into a list for later use
numbers.append(num)
# perform calculations
total = 0
for num in numbers:
total += num
average = total / len(numbers)代码的问题是num是一个float,您不能遍历它。
发布于 2021-01-04 22:28:34
这是一个简单的解决方案
fh = open(<filename>)
total = 0
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") : continue
num = float(line[20 : ])
total += n
print(total)https://stackoverflow.com/questions/65564223
复制相似问题