Skip to main content
 首页 » 编程设计

MATLAB 的 "cellfun"的 Python 或 Numpy 方法

2025年05月04日14jpfss

是否有类似于 MATLAB“cellfun”的 python 或 numpy 方法?我想将一个函数应用于一个对象,该对象是一个 MATLAB 元胞数组,具有约 300k 个不同长度的元胞。

一个非常简单的例子:

>>> xx = [(4,2), (1,2,3)] 
>>> yy = np.exp(xx) 
 
Traceback (most recent call last): 
File "<pyshell#47>", line 1, in <module> 
yy = np.exp(xx) 
AttributeError: 'tuple' object has no attribute 'exp' 

请您参考如下方法:

最可读/可维护的方法可能是使用 list comprehension :

yy = [ np.exp(xxi) for xxi in xx ] 

这依赖于 numpy.exp 将每个元组隐式转换为 numpy.ndarray,这反过来意味着您将获得一个 numpy 列表.ndarray 返回而不是元组列表。对于几乎所有目的来说,这可能没问题,但如果你绝对必须有元组,那也很容易安排:

yy = [ tuple(np.exp(xxi)) for xxi in xx ] 

出于某些目的(例如,为了避免内存瓶颈),您可能更喜欢使用 generator expression而不是列表理解(圆括号而不是方括号)。