Python () vs [] vs {} 之间有什么区别?

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

What's the difference between () vs [] vs {}?

pythondata-structurescollections

提问by Zolomon

What's the difference between () vs [] vs {} in Python?
They're collections? How can I tell when to use which?

Python 中的 () 与 [] 与 {} 之间有什么区别?
他们是收藏品?我怎么知道什么时候使用哪个?

采纳答案by Greg Hewgill

() - 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).

字典是键值对列表,具有唯一键(可变)。从 Python 2.7/3.1 开始,{}也可以表示一组唯一值(可变)。

回答by Mark Byers

  • () is a tuple: An immutable collection of values, usually (but not necessarily) of different types.
  • [] is a list: A mutable collection of values, usually (but not necessarily) of the same type.
  • {} is a dict: Use a dictionary for key value pairs.
  • () 是一个元组:一个不可变的值集合,通常(但不一定)是不同类型的。
  • [] 是一个列表:一个可变的值集合,通常(但不一定)是相同类型的。
  • {} 是一个字典:对键值对使用字典。

For the difference between lists and tuples see here. See also:

有关列表和元组之间的区别,请参见此处。也可以看看:

回答by user225312

() - tuple
[] - list
{} - dictionary

All Python tutorials should cover this. Hereis a good place to start.

所有 Python 教程都应该涵盖这一点。是一个很好的起点。

回答by Andrew Jaffe

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).

除了其他答案给出的元组,列表和字典之外,{}还表示python 2.7和python 3.1中的集合文字。(这是有道理的,因为 set 元素就像字典的键一样)。