【问题标题】:Print out the averages of each list, within the list, one per line in Python打印出每个列表的平均值,在列表中,Python 中每行一个
【发布时间】:2015-12-21 12:22:11
【问题描述】:

我定义了我必须定义的函数,其中参数是一个列表,其中包含列表。前任。平均([[1,2,3],[4,5],[6,7,8,9]])

def avg(lst):

我试过了:

def avg(lst):
    return sum(lst) / float(len(lst))

但我不知道如何遍历列表以平均各个列表...

【问题讨论】:

  • 你期望输出什么?
  • lst 中每个列表的平均值,每行一个。我编程的第一周有点迷茫。

标签: python list function loops average


【解决方案1】:

此解决方案将要求您遍历顶级列表中包含的每个列表。

def avg(lsts):
    for lst in lsts:
        print(sum(lst)/len(lst))

【讨论】:

  • 这就是我的想法!但是当我运行它时,我得到了这个错误:TypeError: unsupported operand type(s) for +: 'float' and 'str'
【解决方案2】:

如果您有一个空的子列表:

In [12]: lst = [[1,2,3], [4,5], [6,7,8,9], []]

In [13]: [sum(x) / float(len(x)) if len(x) else None for x in lst]
Out[13]: [2.0, 4.5, 7.5, None]

【讨论】:

    猜你喜欢
    • 2022-07-07
    • 1970-01-01
    • 2022-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多