把数字1加到一个集合中有n

2024-05-16 04:26:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我无法将整数1添加到现有集合中。在交互式shell中,我正在做的是:

>>> 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}

这个问题是两个月前贴出来的,但我相信被误解了。 我使用的是python3.2.3。在


Tags: thenoaddtruehere整数shellelse
3条回答

1等效于True,因为1 == True返回true。因此,1的插入被拒绝,因为集合不能有重复项。在

>>> 1 == True
True

我相信您的问题是1和{}是相同的值,所以1是“已经在集合中”。在

^{pr2}$

在数学运算中,True本身被视为1

>>> 5 + True
6
>>> True * 2
2
>>> 3. / (True + True)
1.5

虽然True是bool,1是int:

>>> type(True)
<class 'bool'>
>>> type(1)
<class 'int'>

因为1 in st返回True,所以我认为您应该不会有任何问题。但这是一个非常奇怪的结果。如果您对进一步阅读感兴趣,@Lattyware指向PEP 285,它对这个问题进行了深入的解释。在

我相信,尽管我不确定,因为hash(1) == hash(True)和{}它们被{}视为相同的元素。我不认为应该是这样,因为1 is True是{},但我相信这解释了为什么不能添加它。在

相关问题 更多 >