[英]Finding the mean length of an array in a string Python
I am a student VERY new to python and I have no idea how to write a function that calculates the mean length of an array in a string.我是 Python 的新手,我不知道如何编写一个函数来计算字符串中数组的平均长度。 Any help or guidance would be greatly appreciated.
任何帮助或指导将不胜感激。 We are given
我们被赋予
def mean_length(lst):
The tests are测试是
assert mean_length(['fee','freed',free']) == 4
assert mean_length(['alpha', 'beta', 'gamma', 'delta', 'epsilon']) == 5.2
assert mean_length([]) == 0
I have tried我试过了
def mean_length(lst):
x = lst.count(''.join(lst))
y = int(3)
mean = x / y
return mean
There's already a function in the statistics
library that can do this just map len
to the list so you supply it the lengths. statistics
库中已经有一个函数可以执行此操作,只需将len
映射到列表,然后您就可以为其提供长度。
l = ['fee','freed','free']
statistics.mean(map(len, l))
The answer is just a one-liner:答案只是一条线:
def mean_length(l):
return len(''.join(l))/len(l)
Here we are joining all the string in the list and counting the total number of characters and finally dividing it by the total number of elements in the list
, thereby, giving us mean length of words.在这里,我们连接列表中的所有字符串并计算字符总数,最后将其除以
list
中元素的总数,从而得到单词的平均长度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.