python - Python中数字向量或数字列表的平均值

标签 python function average

我是 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

就像 minmax 函数一样?

最佳答案

您可以使用 *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

关于python - Python中数字向量或数字列表的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12551217/

相关文章:

SQL 查询..使用 DISTINCT 和 SUM 对 AVG 和 MEDIAN 有一点帮助

python - 基于 Unicode 值创建数值的简单 Python 程序,需要提示以简化我的代码

python - 奇点容器中的错误 "no free space in/var/cache/apt/archives",但磁盘未满

python - 如何将数据写入 Redshift,这是在 Python 中创建的数据框的结果?

excel - 具有精确 OR 值的嵌套 IF 语句

xcode - swift Xcode 6 : How do I use multiple functions in one statement?

java - 获取二维数组内平方的平均值

python - 重新组织 CSV,使日期不是列标题

c++ - 指针/动态内存分配函数错误(Xcode 到 Linux)

javascript - 以相同的精度计算两个数字的平均值