fix(guide): simplify directory structure

This commit is contained in:
Mrugesh Mohapatra
2018-10-16 21:26:13 +05:30
parent f989c28c52
commit da0df12ab7
35752 changed files with 0 additions and 317652 deletions

View File

@ -0,0 +1,130 @@
---
title: The Python Dict
localeTitle: Python Dict
---
python中的Dictionary又名“dict”是一种内置数据类型可用于存储**`key-value`**对。这允许您将**`dict`**视为存储和组织数据的_数据库_ 。
关于字典的特殊之处在于它们的实现方式。类似哈希表的结构使其易于检查 存在 - 这意味着我们可以轻松确定字典中是否存在特定键而无需检查 每个元素。 Python解释器只需转到位置键并检查密钥是否存在。
字典几乎可以使用任意数据类型,如字符串,整数等,用于键。但是,不可清除的值, 也就是说,包含列表,字典或其他可变类型(通过值而不是通过对象标识进行比较)的值不能用作键。用于键的数字类型遵循用于数字比较的常规规则:如果两个数字比较相等(例如`1``1.0` ),则它们可以互换地用于索引相同的字典条目。 (但请注意,由于计算机将浮点数存储为近似值,因此将它们用作字典键通常是不明智的。)
字典的一个最重要的要求是密钥**必须**是唯一的。
要创建一个空字典,只需使用一对大括号:
```python
>>> teams = {}
>>> type(teams)
>>> <class 'dict'>
```
要创建包含一些初始值的非空字典,请放置以逗号分隔的键值对列表:
```python
>>> teams = {'barcelona': 1875, 'chelsea': 1910}
>>> teams
{'barcelona': 1875, 'chelsea': 1910}
```
将键值对添加到现有字典很容易:
```python
>>> teams['santos'] = 1787
>>> teams
{'chelsea': 1910, 'barcelona': 1875, 'santos': 1787} # Notice the order - Dictionaries are unordered !
>>> # extracting value - Just provide the key
...
>>> teams['barcelona']
1875
```
**`del`**运算符用于从dict中删除键值对。在已经使用的密钥再次用于存储值的情况下与该密钥关联的旧值完全丢失。另外请记住使用不存在的密钥提取值是错误的。
```python
>>> del teams['santos']
>>> teams
{'chelsea': 1910, 'barcelona': 1875}
>>> teams['chelsea'] = 2017 # overwriting
>>> teams
{'chelsea': 2017, 'barcelona': 1875}
```
**`in`** keyword可用于检查dict中是否存在密钥
```python
>>> 'sanots' in teams
False
>>> 'barcelona' in teams
True
>>> 'chelsea' not in teams
False
```
**`keys`**是一种内置_方法_ 可用于获取给定字典的键。要将dict中存在的键提取为列表
```python
>>> club_names = list(teams.keys())
>>> club_names
['chelsea', 'barcelona']
```
另一种创建字典的方法是使用**`dict()`**方法:
```python
>>> players = dict( [('messi','argentina'), ('ronaldo','portugal'), ('kaka','brazil')] ) # sequence of key-value pair is passed
>>> players
{'ronaldo': 'portugal', 'kaka': 'brazil', 'messi': 'argentina'}
>>>
>>> # If keys are simple strings, it's quite easier to specify pairs using keyword arguments
...
>>> dict( totti = 38, zidane = 43 )
{'zidane': 43, 'totti': 38}
```
也可以使用Dict理解来从任意键和值表达式创建字典
```python
>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
```
**在词典中循环**
简单地循环遍历字典中的键,而不是键和值:
```python
>>> d = {'x': 1, 'y': 2, 'z': 3}
>>> for key in d:
... print(key) # do something
...
x
y
z
```
要循环键和值,您可以使用以下内容:
对于Python 2.x
```python
>>> for key, item in d.iteritems():
... print items
...
1
2
3
```
对Python 3.x使用**`items()`**
```python
>>> for key, item in d.items():
... print(key, items)
...
x 1
y 2
z 3
```

View File

@ -0,0 +1,118 @@
---
title: Python Floating Point Numbers
localeTitle: Python浮点数
---
有关浮点数的一般信息以及它们如何在Python中工作可以在[这里](https://docs.python.org/3/tutorial/floatingpoint.html)找到。
几乎所有Python的实现都遵循IEEE 754规范二进制浮点运算标准。更多信息可在[IEEE网站](http://grouper.ieee.org/groups/754/)上找到。
可以使用[浮点文字](https://docs.python.org/3/reference/lexical_analysis.html#floating-point-literals)创建浮动对象:
```
>>> 3.14
3.14
>>> 314\. # Trailing zero(s) not required.
314.0
>>> .314 # Leading zero(s) not required.
0.314
>>> 3e0
3.0
>>> 3E0 # 'e' or 'E' can be used.
3.0
>>> 3e1 # Positive value after e moves the decimal to the right.
30.0
>>> 3e-1 # Negative value after e moves the decimal to the left.
0.3
>>> 3.14e+2 # '+' not required but can be used for exponent part.
314.0
```
数字文字不包含符号,但是可以通过在文字前面没有空格的一元`-` (减号)运算符作为前缀来创建负浮点对象。
```
>>> -3.141592653589793
-3.141592653589793
>>> type(-3.141592653589793)
<class 'float'>
```
同样,正浮点对象可以使用一元`+ (`加号)运算符作为前缀,在文字前没有空格。通常`+`省略:
```
>>> +3.141592653589793
3.141592653589793
```
请注意,前导零和尾随零对浮点文字有效
```
>>> 0.0
0.0
>>> 00.00
0.0
>>> 00100.00100
100.001
>>> 001e0010 # Same as 1e10
10000000000.0
```
[`float`构造函数](https://docs.python.org/3/library/functions.html#float)是另一种创建`float`对象的方法。
在可能的情况下,首选创建具有浮点文字的`float`对象:
```
>>> a = 3.14 # Prefer floating point literal when possible.
>>> type(a)
<class 'float'>
>>> b = int(3.14) # Works but unnecessary.
>>> type(b)
<class 'float'>
```
但是float构造函数允许从其他数字类型创建float对象
```
>>> a = 4
>>> type(a)
<class 'int'>
>>> print(a)
4
>>> b = float(4)
>>> type(b)
<class 'float'>
>>> print(b)
4.0
>>> float(400000000000000000000000000000000)
4e+32
>>> float(.00000000000000000000000000000004)
4e-32
>>> float(True)
1.0
>>> float(False)
0.0
```
`float`构造函数还将从表示数字文字的字符串中创建`float`对象:
```
>>> float('1')
1.0
>>> float('.1')
0.1
>>> float('3.')
3.0
>>> float('1e-3')
0.001
>>> float('3.14')
3.14
>>> float('-.15e-2')
-0.0015
```
`float`构造函数也可用于表示`NaN` (非数字),负`infinity``infinity`数字表示(注意这些字符串不区分大小写):
```
>>> float('nan')
nan
>>> float('inf')
inf
>>> float('-inf')
-inf
>>> float('infinity')
inf
>>> float('-infinity')
-inf
```

View File

@ -0,0 +1,18 @@
---
title: The Python Data Structures
localeTitle: Python数据结构
---
数据结构是在计算机中组织数据的特定方式,以便可以有效地使用它。 Python带有一组强大的内置数据结构。一些最常用的是 -
* 清单
* 元组
* 字典
主要是,数据结构可分为两类: -
* 可变: - 可变数据结构是一种结构,其状态可在创建后进行修改。 Python列表和字典是可变的。
* 不可变: - 不可修改不可变数据结构。示例: - 创建元组后,我们无法更新其中的值。
## 参考:
[Python数据结构](https://docs.python.org/3.7/tutorial/datastructures.html)

View File

@ -0,0 +1,165 @@
---
title: Python Integers
localeTitle: Python整数
---
python中整数的理论域是负无穷大到无穷大。实际上整数值受可用内存量的限制。
在Python 2中 **`int`** 数字适合32或64位_C长_ ,而**`long`**数字受可用内存限制。 Python 3将这两种类型统一为**`int`** ,更多信息在[PEP 237中](https://www.python.org/dev/peps/pep-0237/) 。
**使用整数文字创建`int`**
[整数文字](https://docs.python.org/3/reference/lexical_analysis.html#integer-literals)
可以使用整数文字创建_整数对象_ 。没有小数的简单数字是整数文字:
```
>>> 1234567890 # Unadorned numbers are integer literals
1234567890
>>> type(1234567890)
<class 'int'>
```
数字文字不包含符号,但是可以通过在文字前面没有空格的一元`-` 减号运算符作为前缀来创建负_整数对象_
```
>>> -1234567890
-1234567890
>>> type(-1234567890)
<class 'int'>
```
同样,可以通过在一元`+` (加号)运算符前面添加数字之前没有空格来创建正整数对象。通常`+`被忽略:
```
>>> +1234
1234
```
二进制基数2前缀 `0b``0B` 八进制基数8前缀 `0o``0O` 和十六进制基数16前缀 `0x``0X` )整数也可以使用整数文字创建:
```
>>> 0b1, 0b10, 0b11
(1, 2, 3)
>>> 0o1, 0o10, 0o11
(1, 8, 9)
>>> 0x1, 0x10, 0x11
(1, 16, 17)
```
请注意, **不允许使用**前导0表示非零整数文字
```
>>> 0 # Zero by itself is okay.
0
>>> 01 # Leading zero(s) cause SyntaxError.
File "<stdin>", line 1
01
^
SyntaxError: invalid token
```
`int` [构造函数](https://docs.python.org/3/library/functions.html#int)是另一种创建_整数对象的方法_ 。
```
class int(x=0)
class int(x, base=10)
```
在可能的情况下首选创建具有整数文字的_整数对象_
```
>>> a = 1 # Prefer integer literal when possible.
>>> type(a)
<class 'int'>
>>> b = int(1) # Works but unnecessary.
>>> type(b)
<class 'int'>
```
但是构造函数允许从其他数字类型创建_整数对象_
```
>>> a = 1.123
>>> type(a)
<class 'float'>
>>> print(a)
1.123
>>> b = int(1.123)
>>> type(b)
<class 'int'>
>>> print(b)
1
```
对浮点数使用`int`构造函数会将数字截断为零:
```
>>> int(-1.23)
-1
>>> int(1.23)
1
```
内置的`boolean`常量是`bool`类的实例,并且是`int`类的子类,使它们成为一种数字类型:
```
>>> type(True)
<class 'bool'>
>>> issubclass(bool, int)
True
```
如果这对你没有意义,请不要担心。现在只记得用`boolean`对象调用int构造函数将返回_整数对象_
```
>>> int(True)
1
>>> int(False)
0
```
`int`构造函数还将从字符串中生成_整数对象_
```
>>> a = "10"
>>> type(a)
<class 'str'>
>>> b = int("10")
>>> type(b)
<class 'int'>
```
`int`构造函数的_字符串_必须表示整数文字
`int`构造函数的第二个参数是指定一个base默认值10。有效基数为0和2-36。
如果提供了显式基数,则第一个参数必须是字符串。
```
>>> int("111", 2)
7
>>> int(111, 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: int() can't convert non-string with explicit base
```
用于具有显式基础的`int`构造函数的字符串必须是该基数的有效整数文字:
```
>>> int('11', 2)
3
>>> int('12', 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 2: '12'
```
可以使用前缀和非前缀的整数文字字符串,但是,如果使用,前缀必须与提供的基数匹配。
```
>>> int('1101', 2)
13
>>> int('0b1101', 2)
13
>>> int('0x1101', 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 2: '0x1101'
```
如果使用带前缀的字符串和基数0则创建的整数对象将使用前缀指定的基数。如果没有使用前缀则假定基数为10
```
>>> int('100', 0)
100
>>> int('0b100', 0)
4
>>> int('0o100', 0)
64
```

View File

@ -0,0 +1,116 @@
---
title: The Python Objects
localeTitle: Python对象
---
> 在Python中一切都是_对象_ 。
_对象_表示属性的逻辑分组。属性是数据和/或功能。在Python中创建对象时将使用_标识_ _类型_和_值_创建对象。
在其他语言中, _原始数据_是没有_属性_ (属性) _值_ 。例如在javascript `undefined` `null` `boolean` `string` `number``symbol` ECMAScript 2015中的新内容是原语。
在Python中没有原语。 `None` _布尔值_ _字符串_ _数字_甚至_函数_都是_对象_无论它们是如何创建的。
我们可以使用一些内置函数来演示:
* [`id`](https://docs.python.org/3/library/functions.html#id)
* [`type`](https://docs.python.org/3/library/functions.html#type)
* [`dir`](https://docs.python.org/3/library/functions.html#dir)
* [`issubclass`](https://docs.python.org/3/library/functions.html#issubclass)
内置常量`None` `True``False`是_对象_
我们在这里测试`None`对象。
```python
>>> id(None)
4550218168
>>> type(None)
<class 'NoneType'>
>>> dir(None)
[__bool__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
>>> issubclass(type(None), object)
True
```
接下来,让我们检查一下`True`
```python
>>> id(True)
4550117616
>>> type(True)
<class 'bool'>
>>> dir(True)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
>>> issubclass(type(True), object)
True
```
没理由遗漏`False`
```python
>>> id(False)
4550117584
>>> type(False)
<class 'bool'>
>>> dir(False)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
>>> issubclass(type(False), object)
True
```
_字符串_ 即使通过字符串文字创建的也是_对象_ 。
```python
>>> id("Hello campers!")
4570186864
>>> type('Hello campers!')
<class 'str'>
>>> dir("Hello campers!")
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> issubclass(type('Hello campers!'), object)
True
```
与_数字_相同
```python
>>> id(42)
4550495728
>>> type(42)
<class 'int'>
>>> dir(42)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
>>> issubclass(type(42), object)
True
```
## 功能也是对象
> 在Python中函数是第一类对象。
Python中的_函数_也是使用_标识_ _类型_和_值_创建的_对象_ 。它们也可以传递给其他_函数_
```python
>>> id(dir)
4568035688
>>> type(dir)
<class 'builtin_function_or_method'>
>>> dir(dir)
['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__']
>>> issubclass(type(dir), object)
True
```
也可以将函数绑定到名称,并使用该名称调用绑定函数:
```python
>>> a = dir
>>> print(a)
<built-in function dir>
>>> a(a)
['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__']
```
资源:
* [点击这里](https://www.jeffknupp.com/blog/2014/06/18/improve-your-python-python-classes-and-object-oriented-programming/)了解更多信息。

View File

@ -0,0 +1,87 @@
---
title: The Python Range
localeTitle: Python范围
---
## Python范围
范围实际上是[不可变的序列类型](https://docs.python.org/3/library/stdtypes.html#immutable-sequence-types) 而不是函数通常用于在for循环中循环特定次数。
**创建:**
`ranges`是使用`range`构造函数创建的。构造函数的参数是:
* `start` 包含范围的第一个值可选整数默认为0
* `stop` :独占停止值,当提供此值或更大值时,范围停止(必需整数)。
* `step` 添加到当前值以获取下一个值的量可选整数默认为1
```python
>>> range(10) # Only the stop parameter is required.
range(0, 10)
>>> range(0, 10) # Default for start parameter is 0.
range(0, 10)
>>> range(0, 10, 1) # Default for step is 1\. Start parameter is required if
step is needed.
range(0, 10)
```
**例子:**
由于`ranges`是可迭代的,因此可以将它们传递给`list``tuple`构造函数以创建这些类型的序列。使用这个事实,我们可以想象一些例子:
```python
>>> list(range(10)) # range as argument for list constructor.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> tuple(range(10)) # range as argument for tuple constructor.
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
```
零长度`ranges`
```python
>>> list(range(10, 0)) # start greater than stop with postive step.
[]
>>> list(range(10, 10)) # start equal to stop with postive step.
[]
>>> list(range(10, 10, -1)) # start equal to stop with negative step.
[]
>>> list(range(0, 10, -1)) # start less than stop with negative step.
[]
```
带步长参数的`ranges`
```python
>>> list(range(0, 10, 2)) # next value would be 10, stops at 8.
[0, 2, 4, 6, 8]
>>> list(range(0, 10, 3)) # next value would be 12, stops at 9.
[0, 3, 6, 9]
>>> list(range(0, 10, 4)) # next value would be 12, stops at 8.
[0, 4, 8]
>>> list(range(10, 0, -1)) # negative step makes decreasing ranges.
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> list(range(-5, -30, -3)) # negative integers are valid arguments.
[-5, -8, -11, -14, -17, -20, -23, -26, -29]
```
**优点:**
使用`range`的好处是,无论指定的范围有多大,只需要少量内存来存储`range` 即startstop和step的值。在迭代时计算`ranges`的各个值。
```python
>>> import sys
>>> a_range = range(1000000)
>>> a_list = list(a_range)
>>> a_tuple = tuple(a_range)
>>> sys.getsizeof(a_range)
48
>>> sys.getsizeof(a_list)
9000112
>>> sys.getsizeof(a_tuple)
8000048
```
### 更多信息:
[Python Doc - Ranges](https://docs.python.org/3/library/stdtypes.html#ranges)
**TODO方法`ranges`是否实现**

View File

@ -0,0 +1,13 @@
---
title: The Python Scopes
localeTitle: Python范围
---
**TODO注意**
* 这属于代码块和缩进信息附近。
* 这也与变量有关,因为名称查找和绑定与范围有关。
**TODO内容**
* `global`
* `nonlocal`

View File

@ -0,0 +1,36 @@
---
title: The Python Strings
localeTitle: Python字符串
---
Python允许`str`对象或_字符串_以几种不同的方式表达
* 单引号: `'Single quote strings can have "double" quotes inside.'`
* 双引号: `"Double quote strings can have 'single' quotes inside."`
* 三重引用:
```
"""Triple quoted strings can span multiple lines.
Unescaped "double" and 'single' quotes in triple quoted strings are retained."""
'''Triple quoted strings can be 'single'or "double" quotes.
Unescaped newlines are also retained.'''
```
* 不可变:创建后不能直接编辑/更改Python字符串。例如如果您尝试直接重新分配/更改字符串中的第一个字母,则会引发错误。
```
>>> foo = "my string"
>>> foo[0] = "a"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
```
## 参考:
[文本序列类型_str_](https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str)

View File

@ -0,0 +1,196 @@
---
title: The Tuples
localeTitle: 元组
---
## 元组
元组是一系列Python对象。元组是不可变的这意味着它们在创建后不能被修改这与列表不同。
**创建:**
使用一对圆括号`()`创建一个空`tuple`
```shell
>>> empty_tuple = ()
>>> print(empty_tuple)
()
>>> type(empty_tuple)
<class 'tuple'>
>>> len(empty_tuple)
0
```
通过用逗号分隔元素来创建带元素的`tuple` (围绕圆括号, `()` ,可选,但有例外):
```shell
>>> tuple_1 = 1, 2, 3 # Create tuple without round brackets.
>>> print(tuple_1)
(1, 2, 3)
>>> type(tuple_1)
<class 'tuple'>
>>> len(tuple_1)
3
>>> tuple_2 = (1, 2, 3) # Create tuple with round brackets.
>>> print(tuple_2)
(1, 2, 3)
>>> tuple_3 = 1, 2, 3, # Trailing comma is optional.
>>> print(tuple_3)
(1, 2, 3)
>>> tuple_4 = (1, 2, 3,) # Trailing comma in round brackets is also optional.
>>> print(tuple_4)
(1, 2, 3)
```
具有单个元素的`tuple`必须具有尾随逗号(带或不带圆括号):
```shell
>>> not_tuple = (2) # No trailing comma makes this not a tuple.
>>> print(not_tuple)
2
>>> type(not_tuple)
<class 'int'>
>>> a_tuple = (2,) # Single element tuple. Requires trailing comma.
>>> print(a_tuple)
(2,)
>>> type(a_tuple)
<class 'tuple'>
>>> len(a_tuple)
1
>>> also_tuple = 2, # Round brackets omitted. Requires trailing comma.
>>> print(also_tuple)
(2,)
>>> type(also_tuple)
<class 'tuple'>
```
在歧义的情况下需要圆括号(如果元组是更大表达式的一部分):
> 请注意,它实际上是一个逗号,它产生一个元组,而不是括号。括号是可选的,除了空元组情况,或者需要它们以避免语法歧义。例如, `f(a, b, c)`是具有三个参数的函数调用,而`f((a, b, c))`是以3元组作为唯一参数的函数调用。
```shell
>>> print(1,2,3,4,) # Calls print with 4 arguments: 1, 2, 3, and 4
1 2 3 4
>>> print((1,2,3,4,)) # Calls print with 1 argument: (1, 2, 3, 4,)
(1, 2, 3, 4)
>>> 1, 2, 3 == (1, 2, 3) # Equivalent to 1, 2, (3 == (1, 2, 3))
(1, 2, False)
>>> (1, 2, 3) == (1, 2, 3) # Use surrounding round brackets when ambiguous.
True
```
一个`tuple`也可以与创建的`tuple`的构造函数:
```shell
>>> empty_tuple = tuple()
>>> print(empty_tuple)
()
>>> tuple_from_list = tuple([1,2,3,4])
>>> print(tuple_from_list)
(1, 2, 3, 4)
>>> tuple_from_string = tuple("Hello campers!")
>>> print(tuple_from_string)
('H', 'e', 'l', 'l', 'o', ' ', 'c', 'a', 'm', 'p', 'e', 'r', 's', '!')
>>> a_tuple = 1, 2, 3
>>> b_tuple = tuple(a_tuple) # If the constructor is called with a tuple for
the iterable,
>>> a_tuple is b_tuple # the tuple argument is returned.
True
```
**访问`tuple`元素:**
访问`tuples`元素并以与`lists`相同的方式编制索引。
```shell
>>> my_tuple = 1, 2, 9, 16, 25
>>> print(my_tuple)
(1, 2, 9, 16, 25)
```
_零索引_
```shell
>>> my_tuple[0]
1
>>> my_tuple[1]
2
>>> my_tuple[2]
9
```
_包裹索引_
```shell
>>> my_tuple[-1]
25
>>> my_tuple[-2]
16
```
**包装和拆包:**
声明`t = 12345, 54321, 'hello!'`是元组封装的一个例子:值`12345` `54321``'hello!'`在元组中包装在一起。反向操作也是可能的:
```shell
>>> x, y, z = t
```
这足够恰当地称为序列解包,适用于右侧的任何序列。序列解包需要在等号左侧有尽可能多的变量,因为序列中有元素。请注意,多重赋值实际上只是元组打包和序列解包的组合。
```shell
>>> t = 1, 2, 3 # Tuple packing.
>>> print(t)
(1, 2, 3)
>>> a, b, c = t # Sequence unpacking.
>>> print(a)
1
>>> print(b)
2
>>> print(c)
3
>>> d, e, f = 4, 5, 6 # Multiple assignment combines packing and unpacking.
>>> print(d)
4
>>> print(e)
5
>>> print(f)
6
>>> a, b = 1, 2, 3 # Multiple assignment requires each variable (right)
have a matching element (left).
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)
```
**一成不变的:**
`tuples`是不可变的容器,保证**其**对象它们含有不会改变。它并**不能**保证它们包含的对象不会改变:
```shell
>>> a_list = []
>>> a_tuple = (a_list,) # A tuple (immutable) with a list (mutable) element.
>>> print(a_tuple)
([],)
>>> a_list.append("Hello campers!")
>>> print(a_tuple) # Element of the immutable is mutated.
(['Hello campers!'],)
```
**用途:**
函数只能返回单个值,但是,异构`tuple`可用于从函数返回多个值。一个例子是内置的`enumerate`函数,它返回一个可迭代的异构`tuples`
```shell
>>> greeting = ["Hello", "campers!"]
>>> enumerator = enumerate(greeting)
>>> enumerator.next()
>>> enumerator.__next__()
(0, 'Hello')
>>> enumerator.__next__()
(1, 'campers!')
```
### 更多信息:
[Python文档 - 元组](https://docs.python.org/3/library/stdtypes.html#tuples)