我对 python 相当陌生,并试图弄清楚如何重写下面的平方函数以接受列表作为参数,但我无法让它工作。我想我需要使用称为map或reduce之类的东西。有谁知道应该如何重写以接受列表?
def square(self,x):
number_types = (int, long, float, complex)
if isinstance(x, number_types):
return x*x
else:
raise ValueError
最佳答案
使用 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
对于较大的列表,性能领先会更大。
关于python - 如何重写这个 python 函数以接受列表作为参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45120149/