将数字 1 添加到集合中无效 [英] Adding the number 1 to a set has no effect

查看:51
本文介绍了将数字 1 添加到集合中无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

<预><代码>>>>st = {'a', True, '香草'}>>>英石{'a', True, '香草'}>>>st.add(1)>>>英石{'a', True, 'Vanilla'} # 问题来了;没有 1,但其他任何东西都有效>>>st.add(2)>>>英石{'a', 真, '香草', 2}

这个问题是两个月前发布的,但我相信它被误解了.我使用的是 Python 3.2.3.

解决方案

>>>1 == 真真的

我相信你的问题是 1True 是相同的值,所以 1 是已经在集合中".

<预><代码>>>>英石{'a', True, '香草'}>>>第 1 名真的

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

<预><代码>>>>5 + 真6>>>真 * 22>>>3./(真+真)1.5

虽然 True 是一个布尔值而 1 是一个整数:

<预><代码>>>>类型(真)<类'布尔'>>>>类型(1)<类'int'>

因为 1 in st 返回 True,我认为你应该不会有任何问题.虽然这是一个非常奇怪的结果.如果您有兴趣进一步阅读,@Lattyware 指向 PEP 285深入解释了这个问题.

I cannot add the integer number 1 to an existing set. In an interactive shell, this is what I am doing:

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

This question was posted two months ago, but I believe it was misunderstood. I am using Python 3.2.3.

解决方案

>>> 1 == True
True

I believe your problem is that 1 and True are the same value, so 1 is "already in the set".

>>> st
{'a', True, 'Vanilla'}
>>> 1 in st
True

In mathematical operations True is itself treated as 1:

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

Though True is a bool and 1 is an int:

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

Because 1 in st returns True, I think you shouldn't have any problems with it. It is a very strange result though. If you're interested in further reading, @Lattyware points to PEP 285 which explains this issue in depth.

这篇关于将数字 1 添加到集合中无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆