元组:类似列表(当成容器)
- 特点
1.定义符号()
2.元组中的内容不可以修改
3.关键字:tuple
1. 与列表的区别
t1 = ()
print(type(t1)) # 返回 <class 'tuple'>
t1 = []
print(type(t1)) # 返回 <class 'list'>
t1 = [1]
print(type(t1)) # 返回 <class 'list'>
t1 = [1,]
print(type(t1)) # 返回 <class 'list'>
# 不加逗号与不加括号的类型相同
t2 = (1)
print(type(t2)) # 返回 <class 'int'>
t2 = (1,)
print(type(t2)) # 返回 <class 'tuple'>
t2 = ('hello')
print(type(t2)) # 返回 <class 'str'>
t2 = ('hello',)
print(type(t2)) #返回 <class 'tuple'>
t3 = ("aa", "bb")
print(type(t3)) # 返回 <class 'tuple'>
2. 元组的 增删改 可以通过列表进行
import random
list1 = []
for i in range(10):
ran = random.randint(1, 10)
list1.append(ran)
print(list1) # 返回 [4, 3, 8, 6, 6, 8, 1, 1, 3, 6]
t5 = tuple(list1)
print(t5) # 返回 (4, 3, 8, 6, 6, 8, 1, 1, 3, 6)
3. 元组—查询
t5 = (4, 3, 8, 6, 6, 8, 1, 1, 3, 6)
print(t5[0]) # 返回 4
print(t5[-1]) # 返回 6
print(t5[2:-3]) # 返回 (8, 6, 6, 8, 1)
print(t5[::-1]) # 返回 (6, 3, 1, 1, 8, 6, 6, 8, 3, 4)
4. 最大值 最小值
t5 = (4, 3, 8, 6, 6, 8, 1, 1, 3, 6)
print(max(t5)) # 返回最大值 8
print(min(t5)) # 返回最小值 1
5. 求和
t5 = (4, 3, 8, 6, 6, 8, 1, 1, 3, 6)
print(sum(t5)) # 返回 46
6. 长度
t5 = (4, 3, 8, 6, 6, 8, 1, 1, 3, 6)
print(len(t5)) # 返回 10
7. 元组自带的函数
t5 = (4, 3, 8, 6, 6, 8, 1, 1, 3, 6)
print(t5.count(1)) # 返回 2
#从t5这个元组中找出7的下标位置(第一次出现的位置)
print(t5.index(7)) # 返回 ValueError: tuple.index(x): x not in tuple
print(t5.index(6)) # 返回 3
8. 拆包(unpack)
t1 = (4, 7, 3)
a, b = t1
# ValueError: too many values to unpack (expected 2)
x, y, z = (6,)
# ValueError: not enough values to unpack (expected 3, got 1)
a, b, c = t1
print(a)
print(b)
print(c) # 返回 4 7 3
8. 变量个数与元组个数不一致
t1 = (2, 5, 8, 9, 7)
a, *_, b = t1
print(a, b, _) # 返回 2 7 [5, 8, 9]
a, b, *_ = t1
print(a, b, _) # 返回 2 5 [8, 9, 7]
# *后面是可变的
a, b, *c = t1
print(a, b, c) # 返回 2 5 [8, 9, 7]
# 拆包
print(*c) # 返回 8 9 7
t1 = (9,)
a, *b = t1 # *b 表示未知个数 0~n
print(a, b) # 返回 9 []
9. 符号:+ (连接)*(复制)is/is not (比较地址) in/not in(指定元素是否存在于元组中)
10. 排序 sorted ()-------返回列表
t1 = (2, 5, 8, 9, 7)
t1 = sorted(t1)
print(t1) # 返回 [2, 5, 7, 8, 9]
- 元组:
- 符号:(1,2,3) tuple
- 关键字:tuple
- 元组的元素只能获取,不能增删改
-
符号: + * is/ is not in/ not in
-
系统函数:
max()
min()
sum()
len()
sorted() ----> 排序,返回的结果就是列表
tuple() ---->元组类型的强制转换 -
元组自带函数:
index()
count() -
拆装包:
x,*y =(1,2,3,4,5)
print(y)
print(*y)