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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17373161/
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 08:01:15  来源:igfitidea点击:

Use curly braces to initialize a Set in Python

pythonpython-2.7set

提问by fvrghl

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:

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

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?

还是只是风格问题?

采纳答案by bgporter

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)

  1. 它在 Python 2.7 之前不可用

  2. 无法使用该语法表达空集(使用{}创建空字典)

Those may or may not be important to you.

这些对你来说可能重要也可能不重要。

The section of the docs outlining this syntax is here.

概述此语法的文档部分是here

回答by 0x90

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

Python 3 文档同样适用于 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.

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

in python 2.7:

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

请注意,{}它也用于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', '{', '}'])

回答by Thruston

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

还比较{}set()与单个单词参数之间的差异。

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

but both aand bare sets of course.

但两者ab当然都是套。

回答by Arjjun

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

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