添加号码进行设置
问题描述
我在这里做错了什么?
a = set().add(1)
print a # Prints `None`
我正在尝试将数字 1
添加到空集.
I'm trying to add the number 1
to the empty set.
解决方案
在 Python 中,改变序列的方法返回 None
是一种约定.
It is a convention in Python that methods that mutate sequences return None
.
考虑:
>>> a_list = [3, 2, 1]
>>> print a_list.sort()
None
>>> a_list
[1, 2, 3]
>>> a_dict = {}
>>> print a_dict.__setitem__('a', 1)
None
>>> a_dict
{'a': 1}
>>> a_set = set()
>>> print a_set.add(1)
None
>>> a_set
set([1])
有些人可能认为这种约定在 Python 中是一个可怕的错误设计",但设计和历史常见问题解答 给出了这个设计决策背后的推理(关于列表):
Some may consider this convention "a horrible misdesign in Python", but the Design and History FAQ gives the reasoning behind this design decision (with respect to lists):
为什么 list.sort(
) 不返回排序后的列表?
Why doesn’t
list.sort(
) return the sorted list?
在性能很重要的情况下,制作列表的副本只是为了排序会很浪费.因此,list.sort()
对清单到位.为了提醒你这个事实,它不会返回排序的列表.这样你就不会不小心上当了当您需要排序副本但还需要保留时覆盖列表周围未排序的版本.
In situations where performance matters, making a copy of the list
just to sort it would be wasteful. Therefore, list.sort()
sorts the
list in place. In order to remind you of that fact, it does not return
the sorted list. This way, you won’t be fooled into accidentally
overwriting a list when you need a sorted copy but also need to keep
the unsorted version around.
在 Python 2.4 中添加了一个新的内置函数 - sorted()
.此函数从提供的迭代创建一个新列表,对其进行排序并返回它.
In Python 2.4 a new built-in function – sorted()
– has been added.
This function creates a new list from a provided iterable, sorts it
and returns it.
您对该功能的特殊问题来自对创建集合的好方法的误解,而不是语言设计错误.正如 Lattyware 指出,在 Python 2.7 及更高版本中,您可以使用集合文字 a = {1}
或按照 Sven Marnach 的 answer 执行 a = set([1])
.
Your particular problems with this feature come from a misunderstanding of good ways to create a set rather than a language misdesign. As Lattyware points out, in Python versions 2.7 and later you can use a set literal a = {1}
or do a = set([1])
as per Sven Marnach's answer.
顺便说一句,我喜欢 Ruby 的惯例,即在改变对象的方法之后放置一个感叹号,但我发现 Python 的方法可以接受.
Parenthetically, I like Ruby's convention of placing an exclamation point after methods that mutate objects, but I find Python's approach acceptable.
相关文章