PEP 8: comparison to True should be 'if cond is True:' or 'if cond:'

随声附和 提交于 2020-06-16 05:47:47

问题


PyCharm is throwing a warning when I do np.where(temp == True)

My full code:

from numpy import where, array

a = array([[0.4682], [0.5318]])
b = array([[0.29828851, 0., 0.28676873, 0., 0., 0., 0., 0.28801431, 0., 0., 0.71283046, 0.],
          [0.70171149, 0., 0.71323127, 0., 0., 0., 0., 0.71198569, 0., 0., 0.28716954, 0.]])

temp = b > 1.1*a
pos = where(temp == True)

print(pos) 

The code does not work as expected if I change temp == True to temp is True as suggested in other post.

How should this warning be resolved?

where(temp) works. Thanks a lot !! @Joao Vitorino Thanks for the explanation, @jedwards. It helps.


回答1:


Don't compare boolean against boolean.

You should check if is True or false.

b == true
if b: # If b is True
   do something 

In your case

temp = b > 1.1*a
pos = where(temp)  

Here some explanations




回答2:


As per the PEP8 Guidelines in Python, comparing things to True is not a preferred pattern.

temp = True
pcos = where(temp)

If the 'temp' is assigned to be false, still specifying only 'temp' inside a conditional statement will result True. For instance:

temp = False
pros = while(temp) # if or while condition

NOTE: If your code doesn't follow PEP8, this case will not give any error.



来源:https://stackoverflow.com/questions/50816182/pep-8-comparison-to-true-should-be-if-cond-is-true-or-if-cond

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!