如何重写此 python 函数以接受列表作为参数?

How to rewrite this python function to accept lists as arguments?

我是 python 的新手,正在尝试弄清楚如何在下面重写我的平方函数以接受列表作为参数,但我无法让它工作。我想我需要使用称为 map 或 reduce 之类的东西。有谁知道应该如何重写以接受列表?

def square(self,x):
    number_types = (int, long, float, complex)
    if isinstance(x, number_types):
        return x*x
    else:
        raise ValueError

只需结合使用 lambda 和 map

 l=[1,2,3,4,5,6]


a= lambda x: x*x if type(x) == (int or float or complex) else ""

b=list(map(a,l))

print(b)

[1, 4, 9, 16, 25, 36]

对每个元素求平方:

def square(l):
   return [pow(i, 2) for i in l]

print(square([i for i in range(10)]))

输出:

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

如果你真的需要这样的功能,请制作一个包装器:

def square2(x):
    if isinstance(x, collections.abc.Sequence):
        return [square(n) for n in x]
    return square(x)

对于 Python < 3.3

更改为 collections.Sequence

这是你想要的吗:

class A:
    def square(self, x):
        number_types = (int, long, float, complex)
        xlist = x if isinstance(x, list) else [x]
        for i in xlist:
            if not isinstance(i, number_types):
                raise ValueError
        if not isinstance(x, list):
            return x*x
        return [i*i for i in x]

if __name__ == '__main__':
    a = A()
    print(a.square(2))
    print(a.square([1, 2, 3, 4, 5]))

使用 NumPy

这里最好的解决方案是使用 numpy:

import numpy as np

def square(x):
    x = np.asarray(x)
    number_types = (int, long, float, complex)
    if x.dtype in number_types:
        return x*x
    else:
        raise ValueError

这比在列表上操作更快,并且允许您使用任何类型的可迭代对象。对代码的修改也非常小,代码可读性很强,尤其是与基于 map 的解决方案相比时。

例子

使用标量按预期工作:

>>> square(3)
9

也适用于列表、元组等

>>> square([3, 4])
array([ 9, 16])
>>> square((3, 4))
array([ 9, 16])

性能

与其他版本的快速比较表明它要快得多

>>> a = lambda x: x*x if type(x) == (int or float or complex) else ""
>>> l = [0] * 100
>>> %timeit list(map(a,l))
10000 loops, best of 3: 23.5 µs per loop

>>> %timeit square(l)
100000 loops, best of 3: 6.88 µs per loop

对于更大的列表,性能领先会更大。