添加要设置的号码 [英] Add number to set

查看:70
本文介绍了添加要设置的号码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里做错了什么?

a = set().add(1)print a # 打印 `None`

我正在尝试将数字 1 添加到空集合中.

解决方案

Python 中的一个约定是,改变序列的方法返回 None.

考虑:

<预><代码>>>>a_list = [3, 2, 1]>>>打印 a_list.sort()没有任何>>>一个列表[1, 2, 3]>>>a_dict = {}>>>打印 a_dict.__setitem__('a', 1)没有任何>>>a_dict{'a':1}>>>a_set = set()>>>打印 a_set.add(1)没有任何>>>一套设置([1])

有些人可能认为这个约定是Python 中可怕的错误设计",但设计和历史常见问题解答 给出了这个设计决策背后的推理(关于列表):

<块引用>

为什么list.sort()不返回排序后的列表?

在性能很重要的情况下,复制列表只是排序它会很浪费.因此,list.sort() 对清单到位.为了提醒你那个事实,它不会返回排序后的列表.这样,你就不会不小心上当当您需要排序副本但也需要保留时覆盖列表未排序的版本.

在 Python 2.4 中,添加了一个新的内置函数 - sorted().此函数从提供的可迭代对象创建一个新列表,对其进行排序并返回.

您对此功能的特殊问题来自对创建集合的好方法的误解,而不是语言设计错误.正如 Lattyware 指出,在 Python 2.7 及更高版本中,您可以使用集合文字 a = {1} 或按照 Sven Marnach 的 answer 执行 a = set([1]).

顺便说一句,我喜欢 Ruby 的约定,即在改变对象的方法之后放置一个感叹号,但我发现 Python 的方法是可以接受的.

What am I doing wrong here?

a = set().add(1)
print a # Prints `None`

I'm trying to add the number 1 to the empty set.

解决方案

It is a convention in Python that methods that mutate sequences return None.

Consider:

>>> 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])

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):

Why doesn’t list.sort() return the sorted list?

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.

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.

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.

Parenthetically, I like Ruby's convention of placing an exclamation point after methods that mutate objects, but I find Python's approach acceptable.

这篇关于添加要设置的号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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