使用花括号在Python中初始化Set

问题:使用花括号在Python中初始化Set

我正在学习python,并且对初始化集有一个新手问题。通过测试,我发现可以像这样初始化一个集合:

my_set = {'foo', 'bar', 'baz'}

与标准方式相反,以这种方式进行操作是否有任何缺点:

my_set = set(['foo', 'bar', 'baz'])

还是仅仅是样式问题?

I’m learning python, and I have a novice question about initializing sets. Through testing, I’ve discovered that a set can be initialized like so:

my_set = {'foo', 'bar', 'baz'}

Are there any disadvantages of doing it this way, as opposed to the standard way of:

my_set = set(['foo', 'bar', 'baz'])

or is it just a question of style?


回答 0

设置文字语法有两个明显的问题:

my_set = {'foo', 'bar', 'baz'}
  1. 在Python 2.7之前不可用

  2. 无法使用该语法表示空集(使用{}创建空dict)

这些可能对您很重要,也可能不重要。

概述此语法的文档部分在此处

There are two obvious issues with the set literal syntax:

my_set = {'foo', 'bar', 'baz'}
  1. It’s not available before Python 2.7

  2. There’s no way to express an empty set using that syntax (using {} creates an empty dict)

Those may or may not be important to you.

The section of the docs outlining this syntax is here.


回答 1

也比较之间的差别{},并set()用一个字的说法。

>>> a = set('aardvark')
>>> a
{'d', 'v', 'a', 'r', 'k'} 
>>> b = {'aardvark'}
>>> b
{'aardvark'}

但两者ab都是套路。

Compare also the difference between {} and set() with a single word argument.

>>> a = set('aardvark')
>>> a
{'d', 'v', 'a', 'r', 'k'} 
>>> b = {'aardvark'}
>>> b
{'aardvark'}

but both a and b are sets of course.


回答 2

Python 3文档与python 2.7相同):

花括号或set()函数可用于创建集合。注意:要创建一个空集,您必须使用set()而不是{}; 后者将创建一个空字典,这是我们将在下一节中讨论的数据结构。

在python 2.7中:

>>> my_set = {'foo', 'bar', 'baz', 'baz', 'foo'}
>>> my_set
set(['bar', 'foo', 'baz'])

请注意,{}它也用于map/ dict

>>> m = {'a':2,3:'d'}
>>> m[3]
'd'
>>> m={}
>>> type(m)
<type 'dict'> 

还可以使用综合语法来初始化集:

>>> a = {x for x in """didn't know about {} and sets """ if x not in 'set' }
>>> a
set(['a', ' ', 'b', 'd', "'", 'i', 'k', 'o', 'n', 'u', 'w', '{', '}'])

From Python 3 documentation (the same holds for python 2.7):

Curly braces or the set() function can be used to create sets. Note: to create an empty set you have to use set(), not {}; the latter creates an empty dictionary, a data structure that we discuss in the next section.

in python 2.7:

>>> my_set = {'foo', 'bar', 'baz', 'baz', 'foo'}
>>> my_set
set(['bar', 'foo', 'baz'])

Be aware that {} is also used for map/dict:

>>> m = {'a':2,3:'d'}
>>> m[3]
'd'
>>> m={}
>>> type(m)
<type 'dict'> 

One can also use comprehensive syntax to initialize sets:

>>> a = {x for x in """didn't know about {} and sets """ if x not in 'set' }
>>> a
set(['a', ' ', 'b', 'd', "'", 'i', 'k', 'o', 'n', 'u', 'w', '{', '}'])

回答 3

您需要 empty_set = set()初始化一个空集。{}是空字典。

You need to do empty_set = set() to initialize an empty set. {} is am empty dictionaty.