Py学习  »  Python

在字符串Python中查找数组的平均长度

Amanda Johnson • 4 年前 • 985 次点击  

我是python的新手,我不知道如何编写一个函数来计算字符串中数组的平均长度。任何帮助或指导都将不胜感激。 我们得到了

def mean_length(lst):

测试是

assert mean_length(['fee','freed',free']) == 4
assert mean_length(['alpha', 'beta', 'gamma', 'delta', 'epsilon']) == 5.2
assert mean_length([]) == 0

我试过了

def mean_length(lst):
    x = lst.count(''.join(lst))
    y = int(3)
    mean = x / y
    return mean
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/50909
 
985 次点击  
文章 [ 2 ]  |  最新文章 4 年前
Jab
Reply   •   1 楼
Jab    4 年前

已经有一个函数在 statistics 能做到这一点的图书馆 len 所以你要提供它的长度。

l = ['fee','freed','free']
statistics.mean(map(len, l))
Faiz Kidwai
Reply   •   2 楼
Faiz Kidwai    4 年前

答案只有一句话:

def mean_length(l):
    return len(''.join(l))/len(l)

在这里,我们将连接列表中的所有字符串,并计算字符总数,最后将其除以 list ,因此,给了我们平均长度的单词。