[英]Convert numpy arrays comprehensions to regular python syntax
我不确定是否为标题使用了正确的术语,因为我从未使用过python numpy模块,但是我从特定代码中看到两行,这使我感到困惑:这两个:
IAM[theta == 0]=1
IAM[abs(theta) > 90 | (IAM < 0)]=0
来源: https : //github.com/Sandia-Labs/PVLIB_Python/blob/master/pvlib/pvl_physicaliam.py#L109-111
我想知道是否可以将它们翻译成常规的Python代码? 上两个实际上是否表示:
theta = 10 # for example
newIAM = []
for item in IAM:
if item == 0:
newIAM.append(1)
else:
newIAM.append(item)
和:
newIAM = []
for item in IAM:
if (abs(theta) > 90) and (item < 0)
newIAM.append(0)
else:
newIAM.append(item)
?
我正在使用python 2.7。 感谢您的帮助。
IAM是向量,theta可以是向量或标量。
IAM[theta == 0]=1
将IAM的每个值设置为1,其中相应的theta为零。
IAM[abs(theta) > 90 | (IAM < 0)]=0
(应该)将IAM的每个值设置为0,其中相应的绝对theta值大于90或IAM小于零。
import numpy as np
IAM = np.array( [3, 2, 3, 4, 5] )
# theta can be shorter than IAM
theta = np.array( [0, 1, 0, 1])
IAM[theta==0] = 1
# when theta is a scalar only the fist value will be tested and perhaps changed
# theta[0] is 0 => set IAM[0] to 0
# theta[1] is not 0 => do not change IAM[1]
# ...
#IAM = [1 2 1 4 5]
等效的纯python解决方案:
from itertools import izip_longest
IAM = [3, 2, 3, 4, 5]
theta = [0, 1, 0, 1]
newIAM = []
try:
for iam, t in izip_longest(IAM, theta):
if t == 0:
newIAM.append(1)
else:
newIAM.append(iam)
except TypeError:
newIAM.extend(IAM)
if theta == 0:
neaIAM[0]=1
第二行不能按预期工作。
import numpy as np
IAM = np.array( [-1, 2, 3, -5, 1])
theta = np.array( [1, 2, -91, 3, 4])
IAM[(abs(theta) > 90) | (IAM < 0)]=0
# IAM is [0, 2, 0, 0, 1]
如果没有括号,则abs(theta)> 90,它将检查abs(theta)是否大于(90 |(IAM <0))。 90 | (IAM <0)如果IAM> = 0则求值为90,如果IAM <0则求91。
似乎是您发布的代码中的错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.