使用python求和和平均值

2024-06-13 14:10:08 发布

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

  • 我已经写了一段代码,可以从 文本文件并生成数字列表

  • 我的挑战是对连续的数字求和,然后找到 数字的平均值

  • 我不允许使用sum函数,而且我是python新手。。 这是我到目前为止写的代码

我可以通过列表添加什么

fh = open(fname)
for line in fh:
    if line.startswith("X-DSPAM-Confidence:") : continue
#    print(line)
count = 0
for line in fh:
    if line.startswith("X-DSPAM-Confidence:"):
        count = count + 1
#       print(count)

for line in fh:
    if line.startswith("X-DSPAM-Confidence:"):
#       print(line)
        xpos = line.find(' ')
#       print(xpos)
        num = line[xpos : ]
#       print(float(num))
        fnum = float(num)       
#       print(fnum)
        
        total = 0
        for i in fnum:
            total += int(i) 
            print(total)

错误:“第24行的浮点对象不可编辑”。。。第24行是第4个for循环


Tags: inforifcountline数字numtotal
3条回答

fnum是一个浮点数。它不是数组,因此它是不可iterable的,并且不能在for循环中迭代

您可能不需要数组来确定总数和平均数:

fname = "c:\\mbox-short.txt"
fh = open(fname)

count = 0
total = 0
for line in fh:
    if line.startswith("X-DSPAM-Confidence:"):
        xpos = line.find(' ')
        num = line[xpos : ]
        fnum = float(num)       
        total += fnum
        count += 1

print("Total = " + str(total))
print("Average = " + str(total / count))
print("Number of items = " + str(count))

在这种情况下,您不必使用startsWith。最好对文件的每一行使用拆分。每一行将把所有单词拆分成一个列表。然后使用您查找的索引,X-DSPAM-Confidence:。如果存在,则取相应的兴趣值。在这种情况下,它是索引编号1。代码如下:

total = 0
number_of_items = 0

with open("dat.txt", 'r') as f:
    for line in f:
        fields = line.split()
        if fields != []:
            if fields[0] == "X-DSPAM-Confidence:":
                number_of_items += 1
                total += float(fields[1])

print(total)
print(number_of_items)      

avg = (total/number_of_items)    
print(avg)

我将您的数据保存在一个名为“dat.txt”的文本文件中

希望对你有帮助

首先,一个打开的文件只可编辑一次,代码显示4个以for line in fh:开头的循环。在第一个循环之后,文件指针将到达文件的末尾,下面的循环应该立即返回。因此with应该是首选

接下来在循环中的某个地方,您将在fnum中获得一个浮点值。只需在启动循环之前初始化total,并在得到它时添加fnum

total = 0
with open(fname) as fh:
    for line in fh:
        if line.startswith("X-DSPAM-Confidence:"):
    #       print(line)
            xpos = line.find(' ')
    #       print(xpos)
            num = line[xpos : ]
    #       print(float(num))
            fnum = float(num)       
    #       print(fnum)
            total += fnum
    #       print(total)

with确保文件在循环结束时完全关闭

相关问题 更多 >