blog/docs/code/python/tuple.md

91 lines
1.4 KiB
Markdown
Raw Permalink 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.

---
title: Tuple 元组
date: 2020-07-23 22:43:56
tags: [Python]
categories: [Python]
author: Anges黎梦
---
## 元组 Tuple
Python的元组与列表类似不同之处在于元组的元素不能修改。
元组使用小括号,列表使用方括号。
元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。
## List和Tuple的区别
- list是可以被改变的tuple不可改变
- 只在初始化的时候就定义好tuple元素 添加/删除/更新,这些都不可以。
## 元组创建
```
tuple_1 = (1,2,3,4,5)
```
**元组在只包含一个元素时,需要在元素后面添加一个逗号**
```
tuple_2 = (40, )
print(tuple_1)
print(type(tuple_2))
```
### 任意无符号的对象,以逗号隔开,会被默认为元组
```
tuple_3 = 'abc', 'iii','poi',444,'jf3'
print(tuple_3)
print(type(tuple_3))
```
## 元组查看 等同于 list的[]使用方法
```
print(tuple_1[0])
print(len(tuple_1))
print(max(tuple_1))
print(min(tuple_1))
```
## 元组拼接/组合
```
print(tuple_1+tuple_2)
```
## 删除元组
> 禁止删除其中的某个元素del tuple_1[0]
```
del tuple_2
```
## 重复输出
```
print(tuple_1*3)
```
## 判断包含关系
```
print(3 in tuple_1)
```
## count 元素出现次数
```
print(tuple_1.count(1))
```
## 元素在元组中的序列号index
```
print(tuple_1.index(4))
```