python中的Memberwise运算符

2024-09-22 16:34:45 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在Python中对list(向量)执行成员操作,比如在Matlab/Octave中。我是说,给出两个清单:

a = [1,2,3]
b = [4,5,6]

是否存在成员运算符,例如:

^{pr2}$

我知道我可以自己实现它,如果没有这样的模块我也会这么做。不完全防弹的方法可以是:

# Memberwise product:
def mwprod(a,b):
    c = []
    if len(a) == len(b):
        for a,b in zip(a,b):
            try:
                c.append(a*b)
            except:
                c.append(NaN)
    return c

正如user3426575所述,这可以用一种非常Python的方式浓缩:

c = [ x*y for x, y in zip(a,b)  ]

不管怎样,我想找一个更密集、更美观的方法来重载或实现list上的此类运算符。在


Tags: 模块方法inforlen成员运算符zip
2条回答

你可以这样尝试

>>> [ item * b[k] for k,item in enumerate(a)]
[4, 10, 18]
>>> [ item / b[k] for k,item in enumerate(a)]
[0.25, 0.4, 0.5]

这可以用numpy实现:

>>> import numpy as np
>>> a = np.array([1,2,3],float)  # float argument is used so that / operator does float division rather than integer division
>>> b = np.array([4,5,6],float)
>>> a*b
array([  4.,  10.,  18.])
>>> a/b
array([ 0.25,  0.4 ,  0.5 ])

相关问题 更多 >