()、[]、{} 有什么区别?
Python 中 ()、[] 和 {} 有什么区别?
它们是收藏品吗?我如何知道何时使用哪个?
What's the difference between () vs [] vs {} in Python?
They're collections? How can I tell when to use which?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
() - 元组
元组是不能更改(不可变)的项目序列。
[] - 列表
列表是可以更改(可变)的项目序列。
{} - 字典或集合
字典是键值对的列表,具有唯一的键(可变)。从 Python 2.7/3.1 开始,
{}
还可以表示一组唯一值(可变)。() - tuple
A tuple is a sequence of items that can't be changed (immutable).
[] - list
A list is a sequence of items that can be changed (mutable).
{} - dictionary or set
A dictionary is a list of key-value pairs, with unique keys (mutable). From Python 2.7/3.1,
{}
can also represent a set of unique values (mutable).有关列表和元组之间的区别,请参阅此处。另请参阅:
For the difference between lists and tuples see here. See also:
所有 Python 教程都应该涵盖这一点。 这里是一个很好的起点。
All Python tutorials should cover this. Here is a good place to start.
除了其他答案给出的元组、列表和字典之外,
{}
还表示 python 2.7 和 python 3.1 中的集合文字。 (这是有道理的,因为集合元素的作用就像字典的键)。In addition to the tuple, list and dict given by the other answers,
{}
also denotes a set literal in python 2.7 and python 3.1. (This makes sense because set elements act like the keys of a dict).要完成有关
{}
的其他答案:如果您看到
a = {"key1": 1, "key2": 2, "key3": 3}
(键和值),那么它就是一个dict
。如果您看到
a = {1, 2, 3}
(仅限值),则它是一个集合
。如果您看到
a = {}
(空),则它是一个dict
。使用a = set()
创建一个空的set
。引用官方文档:
To complete the other answers about
{}
:If you see
a = {"key1": 1, "key2": 2, "key3": 3}
(keys and values), then it's adict
.If you see
a = {1, 2, 3}
(values only), then it's aset
.If you see
a = {}
(empty), then it's adict
. An emptyset
is created witha = set()
.Quoting the official doc: