python中表列的平均值

2024-06-01 06:42:36 发布

您现在位置:Python中文网/ 问答频道 /正文

确定代码已创建,输出如下表:

[['              ' '     Scarface ' '     Godfather' '        Avatar']
['Al Pachino    ' '             1' '             1' '            -1']
['Marlon Brando ' '            -1' '             1' '            -1']
['De Niro       ' '            -1' '             1' '            -1']
['Sigorny Weaver' '            -1' '            -1' '             1']]

如何通过编写一个参数为整数a和正整数I的表的函数来获得表列的平均值。该函数应返回a的列I的非负项的平均值

我想用最简单易读的代码来做这个,稍后我可以向孩子们解释。在

谢谢杰玛


Tags: 函数代码参数de平均值alavatargodfather
1条回答
网友
1楼 · 发布于 2024-06-01 06:42:36

用公式<ONLY-POSITIVE-VALUES> / <ALL-INTEGER-COLUMS>求平均值

data = [
    ['              ', '     Scarface ', '     Godfather', '        Avatar'],
    ['Al Pachino    ', '             1', '             1', '            -1'],
    ['Marlon Brando ', '            -1', '             1', '            -1'],
    ['De Niro       ', '            -1', '             1', '            -1'],
    ['Sigorny Weaver', '            -1', '            -1', '             1']
]

def compute_average(row):
    average = 0
    count   = 0
    for column in row:
        count += 1
        try:
            value = int(column)
        except ValueError:
            continue

        if value > 0:
            average += value

    return float(average) / count

for row in data[1:]:
    print compute_average(row)

如果需要类似<ONLY-POSITIVE-VALUES> / <ALL-POSITIVE-VALUES-COLUMS>的公式,只需将count += 1行从for循环的顶部移动到if value > 0语句。在

try/except部分只是因为Python在尝试解析整数形式的非整数字符串时会出现错误,它允许您获取任何数据,而只跳过非整数的数据。在

相关问题 更多 >