将numpy流控制语法转换为常规python语法

时间:2014-11-09 23:37:33

标签: python numpy conditional pvlib

我还有一个关于numpy python模块语法的问题,我想将其转换为常规的python 2.7语法。这是numpy版本:

if any((var.theta < 0) | (var.theta >= 90)):
    print('Input incident angles <0 or >=90 detected For input angles with absolute value greater than 90, the ' + 'modifier is set to 0. For input angles between -90 and 0, the ' + 'angle is changed to its absolute value and evaluated.')
    var.theta[(var.theta < 0) | (var.theta >= 90)]=abs((var.theta < 0) | (var.theta >= 90))

源代码: https://github.com/Sandia-Labs/PVLIB_Python/blob/master/pvlib/pvl_physicaliam.py#L93-95

如果我们假装numpy数组是一维的,那么常规python 2.7语法会是这样的:

newTheta = []
for item in var.theta:
    if (item < 0) and (item >= 90):
        print('Input incident angles <0 or >=90 detected For input angles with absolute value greater than 90, the ' + 'modifier is set to 0. For input angles between -90 and 0, the ' + 'angle is changed to its absolute value and evaluated.')
        newItem = abs(item)
        newTheta.append(newItem)

?? 谢谢你的回复。

1 个答案:

答案 0 :(得分:2)

用语言来说,if any((var.theta < 0) | (var.theta >= 90))表达式意味着什么:&#34;如果var.theta中的任何条目小于零大于或等于90,那么...&#34;

您的控制语句流程是&#34;如果var.theta的条目小于0 大于或等于90,请执行...&#34;。

如果您在普通的Python示例中真的是指,那么是的,它看起来就像这样。或者,你可以使用列表理解:

newTheta = [abs(item) for item in var.theta if (item < 0 or item >= 90)]

列表理解更紧凑,对于简单的操作更容易阅读,并且解释器更容易优化。