Python tuple comparison odd behavior

╄→гoц情女王★ 提交于 2019-12-11 12:42:19

问题


Can someone please explain this behavior?

In[11]: (1, 2) in [(True, 2)]
Out[11]: True

In[12]: (1, 2) in [(True, True)]
Out[12]: False

In[13]: (1, 2) in [(True, False)]
Out[13]: False

In[14]: ("1", 2) in [(True, 2)]
Out[14]: False

It feels like a bug--whenever I check if a tuple is in a list of tuples, the integer 1 is always equal to True. I don't want to report it to the Python bug tracker if it can be explained.


回答1:


It's something of an implementation detail of True, see Is False == 0 and True == 1 in Python an implementation detail or is it guaranteed by the language? for a discussion.




回答2:


The "trick" here I suppose is that 1 == True and 0 == False both evaluate to True.

Your lines 11, 12 and 13 imply that all truthy values should be equal. If that were the case though, 1 == 2 would evaluate to True which would clearly be a bug.



来源:https://stackoverflow.com/questions/33586081/python-tuple-comparison-odd-behavior

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