python中的元组类型
1、元组的特点
-
元组的关键字:tuple
-
定义符号:()
-
元组中的内容不可修改
-
如果元组中只有一个元素,该元素后需要跟一个逗号,否则()不起作用
t1 = () print(type(t1)) # <class 'tuple'> t2 = (10) print(type(t2)) # <class 'int'> t3 = (10,) print(type(t3)) # <class 'tuple'>
2、元组元素的放入
元组不能被修改,即不能增加、修改、删除元组中的元素,但可以通过tuple()来将列表转换成元组类型
import random
# 生成10个随机数的列表
ran_list = []
i = 1
while i <= 10:
ran = random.randint(1, 20)
if ran not in ran_list:
ran_list.append(ran)
i += 1
print(ran_list)
t = tuple(ran_list)
print(t)
3、元组的查询
t = (19, 3, 7, 4, 18, 6, 13, 17, 14, 12)
print(t[3]) # 4
print(t[3:-3]) # (4, 18, 6, 13)
print(t[::-1]) # (12, 14, 17, 13, 6, 18, 4, 7, 3, 19)
print(max(t)) # 19
print(min(t)) # 3
print(sum(t)) # 113
print(len(t)) # 10
4、元组中的函数
-
t.count(value):返回元组t中value出现的次数
t = (19, 3, 7, 4, 18, 3, 13, 17, 14, 12) print(t.count(3)) # 2
-
t.index(value):返回元组t中value第一次出现的下标
t = (19, 3, 7, 4, 18, 3, 13, 17, 14, 12) print(t.index(3)) # 1 print(t.index(5)) # ValueError: tuple.index(x): x not in tuple
5、元组的拆包和装包
t = (5, 8, 1)
a, b = t
print(a, b) # ValueError: too many values to unpack (expected 2)
w, x, y, z = t
print(w, x, y, z) # ValueError: not enough values to unpack (expected 4, got 3)
x, y, z = t
print(x, y, z) # 5 8 1
t1 = (1, 5, 2, 9)
a, *b, c = t1
print(a, c, b) # 1 9 [5, 2]
t2 = (1,)
a, *b = t2
print(a, b) # 1 []