Update 07. 元组.md

This commit is contained in:
LSGOMYP
2020-07-21 10:26:36 +08:00
parent 353918026d
commit b176f59dfc

View File

@@ -8,6 +8,9 @@
- Python 的元组与列表类似不同之处在于tuple被创建后就不能对其进行修改类似字符串。
- 元组使用小括号,列表使用方括号。
- 元组与列表类似,也用整数来对它进行索引 (indexing) 和切片 (slicing)。
【例子】
```python
t1 = (1, 10.31, 'python')
@@ -27,21 +30,21 @@ print(tuple2) # (1, 2, 3, 4, 5, 6, 7, 8)
```
- 创建元组可以用小括号 (),也可以什么都不用,为了可读性,建议还是用 ()。
- 元组中只包含一个元素时,需要在元素后面添加逗号,否则括号会被当作运算符使用
- 元组中只包含一个元素时,需要在元素后面添加逗号,否则括号会被当作运算符使用
【例子】
```python
temp = (1)
print(type(temp)) # <class 'int'>
temp = 2, 3, 4, 5
print(type(temp)) # <class 'tuple'>
temp = []
print(type(temp)) # <class 'list'>
temp = ()
print(type(temp)) # <class 'tuple'>
temp = (1,)
print(type(temp)) # <class 'tuple'>
x = (1)
print(type(x)) # <class 'int'>
x = 2, 3, 4, 5
print(type(x)) # <class 'tuple'>
x = []
print(type(x)) # <class 'list'>
x = ()
print(type(x)) # <class 'tuple'>
x = (1,)
print(type(x)) # <class 'tuple'>
```
【例子】
@@ -51,30 +54,24 @@ print(8 * (8)) # 64
print(8 * (8,)) # (8, 8, 8, 8, 8, 8, 8, 8)
```
【例子】当然也可以创建二维元组
【例子】创建二维元组
```python
nested = (1, 10.31, 'python'), ('data', 11)
print(nested)
x = (1, 10.31, 'python'), ('data', 11)
print(x)
# ((1, 10.31, 'python'), ('data', 11))
```
【例子】元组中可以用整数来对它进行索引 (indexing) 和切片 (slicing),不严谨的讲,前者是获取单个元素,后者是获取一组元素。接着上面二维元组的例子,先看看索引的代码。
```python
print(nested[0])
print(x[0])
# (1, 10.31, 'python')
print(nested[0][0], nested[0][1], nested[0][2])
print(x[0][0], x[0][1], x[0][2])
# 1 10.31 python
```
【例子】再看看切片的代码。
```python
print(nested[0][0:2])
print(x[0][0:2])
# (1, 10.31)
```
## 2. 更新和删除一个元组
【例子】
@@ -85,7 +82,7 @@ week = week[:2] + ('Wednesday',) + week[2:]
print(week) # ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday')
```
【例子】
【例子】元组有不可更改 (immutable) 的性质,因此不能直接给元组的元素赋值,但是只要元组中的元素可更改 (mutable),那么我们可以直接更改其元素,注意这跟赋值其元素不同。
```python
t1 = (1, 2, 3, [4, 5, 6])
print(t1) # (1, 2, 3, [4, 5, 6])
@@ -93,28 +90,41 @@ print(t1) # (1, 2, 3, [4, 5, 6])
t1[3][0] = 9
print(t1) # (1, 2, 3, [9, 5, 6])
```
元组有不可更改 (immutable) 的性质,因此不能直接给元组的元素赋值,但是只要元组中的元素可更改 (mutable),那么我们可以直接更改其元素,注意这跟赋值其元素不同。
## 3. 元组相关的操作符
- 比较操作符
- 逻辑操作符
- 等号操作符`==`
- 连接操作符 `+`
- 重复操作符 `*`
- 成员关系操作符 `in``not in`
【例子】元组拼接 (concatenate) 有两种方式,用「加号 +」和「乘号 *」,前者首尾拼接,后者复制拼接
「等号 ==」只有成员、成员位置都相同时才返回True
元组拼接有两种方式,用「加号 +」和「乘号 *」,前者首尾拼接,后者复制拼接。
【例子】
```python
t1 = (2, 3, 4, 5)
t2 = ('老马的程序人生', '小马的程序人生')
t3 = t1 + t2
print(t3)
# (2, 3, 4, 5, '老马的程序人生', '小马的程序人生')
t1 = (123, 456)
t2 = (456, 123)
t3 = (123, 456)
t4 = t2 * 2
print(t4)
# ('老马的程序人生', '小马的程序人生', '老马的程序人生', '小马的程序人生')
print(t1 == t2) # False
print(t1 == t3) # True
t4 = t1 + t2
print(t4) # (123, 456, 456, 123)
t5 = t3 * 3
print(t5) # (123, 456, 123, 456, 123, 456)
t3 *= 3
print(t3) # (123, 456, 123, 456, 123, 456)
print(123 in t3) # True
print(456 not in t3) # False
```
## 4. 内置方法
@@ -161,6 +171,7 @@ print(rest) # [3, 4]
【例子】如果你根本不在乎 rest 变量,那么就用通配符「*」加上下划线「_」。
```python
t = 1, 2, 3, 4, 5
a, b, *_ = t
print(a, b) # 1 2
```