如果给函数一个列表,则自动使用列表理解/map() 递归

2024-02-05

作为一名 Mathematica 用户,我喜欢自动“遍历列表”的函数(Mathematica 人们称之为 - 请参阅http://reference.wolfram.com/mathematica/ref/Listable.html 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 https://stackoverflow.com/questions/1952464/in-python-how-do-i-determine-if-a-variable-is-iterable是一个有用的 StackOverflow 问题,可以用来确定这一点。不过要小心 - 字符串是可迭代的,但您可能不希望函数对其中的每个字符进行操作。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如果给函数一个列表,则自动使用列表理解/map() 递归 的相关文章

随机推荐