gpt4 book ai didi

MATLAB 的 "cellfun"的 Python 或 Numpy 方法

转载 作者:太空宇宙 更新时间:2023-11-04 08:01:08 25 4
gpt4 key购买 nike

是否有类似于 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而不是列表理解(圆括号而不是方括号)。

关于MATLAB 的 "cellfun"的 Python 或 Numpy 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40007120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com