Python中计算向量或列表的平均数

3

我是一个新手,不太懂Python,请谅解我的问题。

我想写一个函数,它可以接收一组数字,并计算它们的平均值。所以我写了一个小函数:

def my_mean(*args):
    if len(args) == 0:
        return None
    else:
        total = sum(args)
        ave = 1.0 * total / len(args)
        return ave

my_mean(1, 2, 3)
2.0

但如果参数是一组数字,此函数将无法正常工作。例如,
my_mean([1, 2, 3])
Traceback (most recent call last):
  File "/usr/lib/wingide-101-4.1/src/debug/tserver/_sandbox.py", line 1, in <module>
    # Used internally for debug sandbox under external interpreter
  File "/usr/lib/wingide-101-4.1/src/debug/tserver/_sandbox.py", line 21, in my_mean
TypeError: unsupported operand type(s) for +: 'int' and 'list'

我知道NumPy有一个函数numpy.mean,它以列表作为参数,但不像my_mean一样接受数字向量。

我想知道是否有办法使my_mean在这两种情况下都能工作?所以:

my_mean(1, 2, 3)
2.0
my_mean([1, 2, 3])
2.0

就像min或者max函数一样吗?

2个回答

6
你可以使用*arg语法传递列表:
my_mean(*[1, 2, 3])

或者,您可以检测传入的第一个参数是否为序列,并使用该序列代替整个args元组:

import collections

def my_mean(*args):
    if not args:
        return None
    if len(args) == 1 and isinstance(args[0], collections.Container):
        args = args[0]
    total = sum(args)
    ave = 1.0 * total / len(args)
    return ave

啊,不错,我没有考虑到集合 ABCs。不过我会检查是否只有一个参数。否则,“my_mean([1, 2, 3], 4)” 的行为将是意外的(实际上我期望它会出错)。 - Jonas Schäfer
@JonasWielicki:确实;我也更新了空参数测试,使其更简单。 - Martijn Pieters
谢谢您的快速回复。我知道如果我使用my_mean(1, 2, 3),Python会收集所有参数并将它们作为列表传递给args,所以在函数中args是一个包含[1, 2, 3]的列表。我不理解为什么要添加一个*my_mean(*[1, 2, 3])中。您能否再详细解释一下?我在我的书(一本非常入门的书)中找不到这个内容。 - JACKY88
1
查看*args和**kwargs?以及http://docs.python.org/reference/expressions.html#calls - Martijn Pieters

1
为何不将您的列表作为元组传递呢? 使用 func(*[1, 2, 3])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接