作为 Mathematica 用户,我喜欢自动“通过列表串接”的函数(正如 Mathematica 用户所说的那样 - 请参阅 http://reference.wolfram.com/mathematica/ref/Listable.html)。这意味着如果给函数一个列表而不是单个值,它会自动使用每个列表条目作为参数并返回结果列表 - 例如
myfunc([1,2,3,4]) -> [myfunc(1),myfunc(2),myfunc(3),myfunc(4)]
我在 Python 中这样实现了这个原则:
def myfunc(x):
if isinstance(x,list):
return [myfunc(thisx) for thisx in x]
#rest of the function
这样做好吗?您能想到这种实现或整个策略的任何缺点吗?
最佳答案
如果这是您要在很多函数中执行的操作,您可以使用 Python 装饰器。这是一个简单但有用的方法。
def threads_over_lists(fn):
def wrapped(x, *args, **kwargs):
if isinstance(x, list):
return [fn(e, *args, **kwargs) for e in x]
return fn(x, *args, **kwargs)
return wrapped
这样,只需在您的函数之前添加行 @threads_over_lists
即可使其以这种方式运行。例如:
@threads_over_lists
def add_1(val):
return val + 1
print add_1(10)
print add_1([10, 15, 20])
# if there are multiple arguments, threads only over the first element,
# keeping others the same
@threads_over_lists
def add_2_numbers(x, y):
return x + y
print add_2_numbers(1, 10)
print add_2_numbers([1, 2, 3], 10)
您还应该考虑是希望它只对列表进行矢量化,还是对元组和生成器等其他可迭代对象进行矢量化。 This是一个有用的 StackOverflow 问题来确定这一点。不过要小心——字符串是可迭代的,但您可能不希望函数对其中的每个字符进行操作。
关于python - 如果给函数一个列表,自动使用列表推导/map() 递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12175031/