gpt4 book ai didi

python - 添加号码进行设置

转载 作者:IT老高 更新时间:2023-10-28 20:39:00 24 4
gpt4 key购买 nike

我在这里做错了什么?

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

我正在尝试将数字 1 添加到空集。

最佳答案

在 Python 中,改变序列的方法返回 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 中的一个可怕的错误设计”,但设计和历史常见问题解答 gives the reasoning在这个设计决策背后(关于列表):

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.

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

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

关于python - 添加号码进行设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9299919/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com