【问题标题】:Problem to find the length and average of a list array in python在python中查找列表数组的长度和平均值的问题
【发布时间】:2021-11-16 14:02:32
【问题描述】:

我尝试编写一个程序来计算存储在文本文件中的单词的平均长度,每行一个。更多解释程序将读取文件中的单词,找到它们的长度,最后计算平均长度。该文件包含以下单词:Book、List、Python、Masterpiece、National 等。关于所有这些,我编写了以下代码行:

import requests
import os
import math


f = open('C:/tt.txt','r',encoding='utf-8')

#for list in f:
        #f = list.split() 

for list in f:
        a=len(list)
        #print(len(list))
        print(a)
        #b=sum(len(list))
avg=sum(a)/coun(list) #find the average

当程序运行时,单词长度的结果是好的,但不是正确的顺序(例如 5,7,12,9 但它必须是 9,12,5...)。另一个程序是txt文档的内容不能拆分(看代码注释)。编译的结果是:Traceback(最近调用last): 文件“C:\Users\pliroforiki-sox2\Desktop\exercises\4_07.py”,第 17 行,在 avg=sum(list)/count(a) #求平均值 类型错误:+ 不支持的操作数类型:'int' 和 'str'

【问题讨论】:

  • coun(list) 应该是 len(list) 并且不要将变量命名为 list,因为您正在隐藏内置类型名称

标签: python list function average


【解决方案1】:

怎么样?

total = 0
word_count = 0
with open('C:/tt.txt','r',encoding='utf-8') as f:
    for line in f:
        word_length = len(line.strip())
        print(word_length)
        total += word_length
        word_count += 1
print(total / word_count)

请注意,我还使用“with open() as f:”语法,这是更好的做法。这会自动为您处理文件清理。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-17
    • 1970-01-01
    • 1970-01-01
    • 2012-02-20
    相关资源
    最近更新 更多