Python中的大括号和方括号有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22391419/
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
What is the difference between curly brace and square bracket in Python?
提问by Haoyu Chen
what is the difference between curly brace and square bracket in python?
python中的大括号和方括号有什么区别?
A ={1,2}
B =[1,2]
when I print Aand Bon my terminal, they made no difference. Is it real?
当我在终端上打印A和打印时B,它们没有任何区别。这是真的吗?
And sometimes, I noticed some code use {}and []to initialize different variables.
有时,我注意到一些代码使用{}和[]初始化不同的变量。
E.g. A=[], B={}
例如A=[],B={}
Is there any difference there?
有什么区别吗?
采纳答案by Martijn Pieters
Curly braces create dictionariesor sets. Square brackets create lists.
They are called literals; a set literal:
它们被称为文字;一组文字:
aset = {'foo', 'bar'}
or a dictionary literal:
或字典文字:
adict = {'foo': 42, 'bar': 81}
empty_dict = {}
or a list literal:
或列表文字:
alist = ['foo', 'bar', 'bar']
empty_list = []
To create an empty set, you can only use set().
要创建空集,您只能使用set().
Sets are collections of uniqueelements and you cannot order them. Lists are ordered sequences of elements, and values can be repeated. Dictionaries map keys to values, keys must be unique. Set and dictionary keys must meet other restrictions as well, so that Python can actually keep track of them efficiently and know they are and will remain unique.
集合是唯一元素的集合,您无法对它们进行排序。列表是元素的有序序列,值可以重复。字典将键映射到值,键必须是唯一的。集合键和字典键也必须满足其他限制,这样 Python 才能真正有效地跟踪它们并知道它们是唯一的并将保持唯一。
There is also the tupletype, using a comma for 1 or more elements, with parenthesis being optional in many contexts:
还有tupletype,对 1 个或多个元素使用逗号,括号在许多情况下是可选的:
atuple = ('foo', 'bar')
another_tuple = 'spam',
empty_tuple = ()
WARNING_not_a_tuple = ('eggs')
Note the comma in the another_tupledefinition; it is that comma that makes it a tuple, not the parenthesis. WARNING_not_a_tupleis not a tuple, it has no comma. Without the parentheses all you have left is a string, instead.
注意another_tuple定义中的逗号;是那个逗号使它成为tuple,而不是括号。WARNING_not_a_tuple不是元组,它没有逗号。没有括号,您只剩下一个字符串。
See the data structures chapterof the Python tutorial for more details; lists are introduced in the introduction chapter.
有关更多详细信息,请参阅Python 教程的数据结构章节;列表在介绍一章中介绍。
Literals for containers such as these are also called displaysand the syntax allows for procedural creation of the contents based of looping, called comprehensions.
诸如此类的容器的文字也称为显示,其语法允许基于循环程序创建内容,称为理解。
回答by Daenyth
They create different types.
他们创造了不同的类型。
>>> type({})
<type 'dict'>
>>> type([])
<type 'list'>
>>> type({1, 2})
<type 'set'>
>>> type({1: 2})
<type 'dict'>
>>> type([1, 2])
<type 'list'>
回答by ytpillai
These two braces are used for different purposes. If you just want a list to contain some elements and organize them by index numbers (starting from 0), just use the []and add elements as necessary. {}are special in that you can give custom id's to values like a = {"John": 14}. Now, instead of making a list with ages and remembering whose age is where, you can just access John's age by a["John"].
这两个大括号用于不同的目的。如果您只想让列表包含一些元素并按索引号(从 0 开始)组织它们,只需[]根据需要使用和添加元素。{}特殊之处在于您可以为像a = {"John": 14}. 现在,您无需列出年龄并记住谁的年龄在哪里,而只需通过 访问约翰的年龄即可a["John"]。
The []is called a list and {}is called a dictionary (in Python). Dictionaries are basically a convenient form of list which allow you to access data in a much easier way.
在[]被称为列表和{}被称为字典(在Python)。字典基本上是一种方便的列表形式,它允许您以更简单的方式访问数据。
However, there is a catch to dictionaries. Many times, the data that you put in the dictionary doesn't stay in the same order as before. Hence, when you go through each value one by one, it won't be in the order you expect. There is a special dictionary to get around this, but you have to add this line from collections import OrderedDictand replace {}with OrderedDict(). But, I don't think you will need to worry about that for now.
但是,字典有一个问题。很多时候,您放入字典中的数据不会保持与以前相同的顺序。因此,当您一一查看每个值时,它不会按照您期望的顺序进行。有一个特殊的字典可以解决这个问题,但您必须添加这一行from collections import OrderedDict并替换{}为OrderedDict(). 但是,我认为你现在不需要担心这个。

