Python 为什么有时可以用 {} 替换 set()?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36674083/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:12:56  来源:igfitidea点击:

Why is it possible to replace sometimes set() with {}?

pythonset

提问by Olivier Pons

In PyCharm, when I write:

在 PyCharm 中,当我写:

return set([(sy + ady, sx + adx)])

it says "Function call can be replaced with set literal"so it replaces it with:

它说“函数调用可以用设置文字替换所以它替换为:

return {(sy + ady, sx + adx)}

Why is that? A set()in Python is not the same as a dictionary {}?

这是为什么?set()Python 中的A与字典不一样{}

And if it wants to optimize this, why is this more effective?

如果它想优化这一点,为什么这更有效?

回答by snakecharmerb

Python sets and dictionaries can both be constructed using curly braces:

Python 集合和字典都可以使用花括号构造:

my_dict = {'a': 1, 'b': 2}

my_dict = {'a': 1, 'b': 2}

my_set = {1, 2, 3}

my_set = {1, 2, 3}

The interpreter (and human readers) can distinguish between them based on their contents. However it isn't possible to distinguish between an empty set and an empty dict, so this case you need to use set()for empty sets to disambiguate.

解释器(和人类读者)可以根据它们的内容区分它们。但是,无法区分空集和空字典,因此在这种情况下,您需要使用set()空集来消除歧义。

A very simple test suggests that the literal construction is faster (python3.5):

一个非常简单的测试表明文字构造速度更快(python3.5):

>>> timeit.timeit('a = set([1, 2, 3])')
0.5449375328607857
>>> timeit.timeit('a = {1, 2, 3}')
0.20525191631168127

This questioncovers some issues of performance of literal constructions over builtin functions, albeit for lists and dicts. The summary seems to be that literal constructions require less work from the interpreter.

这个问题涵盖了文字构造在内置函数上的一些性能问题,尽管是针对列表和字典。总结似乎是字面结构需要解释器的工作较少。

回答by DhruvPathak

It is an alternative syntax for set()

它是一种替代语法 set()

>>> a = {1, 2}
>>> b = set()
>>> b.add(1)
>>> b.add(2)
>>> b
set([1, 2])
>>> a
set([1, 2])
>>> a == b
True
>>> type(a) == type(b)
True

dictsyntax is different. It consists of key-value pairs. For example:

dict语法不同。它由键值对组成。例如:

my_obj = {1:None, 2:None}

回答by C Panda

set([iterable])is the constructor to create a set from the optional iterable iterable. And {}is to create set / dict object literals. So what is created depends on how you use it.

set([iterable])是从可选的 iterable 创建一个集合的构造函数iterable。并且{}是创建 set / dict 对象文字。所以创建什么取决于你如何使用它。

In [414]: x = {}

In [415]: type(x)
Out[415]: dict

In [416]: x = {1}

In [417]: type(x)
Out[417]: set

In [418]: x = {1: "hello"}

In [419]: type(x)
Out[419]: dict

回答by Emanuel

Another example how setand {}are not interchangeable(as jonrsharpe mentioned):

又如如何set{}不能互换(如jonrsharpe提及):

In: f = 'FH'

In: set(f)
Out: {'F', 'H'}

In: {f}
Out: {'FH'}