Files
notes_estom/Python/python3/2.5元组.md
2020-09-23 13:41:55 +08:00

97 lines
1.4 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Python 元组
> 原文: [https://thepythonguru.com/python-tuples/](https://thepythonguru.com/python-tuples/)
* * *
于 2020 年 1 月 7 日更新
* * *
在 Python 中,元组与列表非常相似,但是一旦创建了元组,就无法添加,删除,替换和重新排序元素。
**注意**
元组是不可变的。
## 创建一个元组
* * *
```py
>>> t1 = () # creates an empty tuple with no data
>>>
>>> t2 = (11,22,33)
>>>
>>> t3 = tuple([1,2,3,4,4]) # tuple from array
>>>
>>> t4 = tuple("abc") # tuple from string
```
## 元组函数
* * *
元组也可以使用`max()``min()``len()``sum()`之类的函数。
```py
>>> t1 = (1, 12, 55, 12, 81)
>>> min(t1)
1
>>> max(t1)
81
>>> sum(t1)
161
>>> len(t1)
5
```
## 元组迭代
* * *
元组可使用`for`循环进行迭代,[在此处了解有关 for 循环的更多信息](/python-loops/)。
```py
>>> t = (11,22,33,44,55)
>>> for i in t:
... print(i, end=" ")
>>> 11 22 33 44 55
```
## 元组切片
* * *
切片运算符在元组中的作用与在列表和字符串中的作用相同。
```py
>>> t = (11,22,33,44,55)
>>> t[0:2]
(11,22)
```
## `in`和`not in`运算符
* * *
您可以使用`in``not in`运算符检查元组中项的存在,如下所示。
```py
>>> t = (11,22,33,44,55)
>>> 22 in t
True
>>> 22 not in t
False
```
在下一章中,我们将学习 [python 数据类型转换](/datatype-conversion/)。
* * *
* * *