将数字1添加到集合中无效
问题内容:
我无法将整数添加1
到现有集合中。在交互式外壳中,这就是我正在做的:
>>> st = {'a', True, 'Vanilla'}
>>> st
{'a', True, 'Vanilla'}
>>> st.add(1)
>>> st
{'a', True, 'Vanilla'} # Here's the problem; there's no 1, but anything else works
>>> st.add(2)
>>> st
{'a', True, 'Vanilla', 2}
这个问题是两个月前发布的,但我认为这是被误解了。我正在使用Python 3.2.3。
问题答案:
>>> 1 == True
True
我相信您的问题是,1
并且True
它们具有相同的值,因此1已“已在集合中”。
>>> st
{'a', True, 'Vanilla'}
>>> 1 in st
True
在数学运算True
中,其本身被视为1
:
>>> 5 + True
6
>>> True * 2
2
>>> 3. / (True + True)
1.5
尽管True是布尔值,1是整数:
>>> type(True)
<class 'bool'>
>>> type(1)
<class 'int'>
因为1 in st
返回True,所以我认为您应该没有任何问题。但是,这是一个非常奇怪的结果。如果您有兴趣进一步阅读,@ Lattyware指向PEP
285
,它详细解释了此问题。