【问题标题】:Finding the mean length of an array in a string Python在字符串 Python 中查找数组的平均长度
【发布时间】:2019-12-06 04:02:31
【问题描述】:

我是一个对 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

【问题讨论】:

  • 一个班轮:def mean_length(xs): return sum(len(x) for x in xs) / len(xs)

标签: python arrays string


【解决方案1】:

statistics 库中已经有一个函数可以做到这一点,只需将 len 映射到列表,以便您为其提供长度。

l = ['fee','freed','free']
statistics.mean(map(len, l))

【讨论】:

  • 我们不允许使用统计库中的函数。不过还是谢谢你的意见。
【解决方案2】:

答案只是一条线:

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

在这里,我们连接列表中的所有字符串并计算字符总数,最后将其除以list 中的元素总数,从而得出平均单词长度。

【讨论】:

    猜你喜欢
    • 2018-01-20
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多