数据类型之元祖

1.定义

在()内用逗号分隔开多个任意类型的值

2.类型转换

# 但凡能被for循环的遍历的数据类型都可以传给tuple()转换成元组类型
>>> tuple('wdad')  					 # 结果:('w', 'd', 'a', 'd') 
>>> tuple([1,2,3]) 					 # 结果:(1, 2, 3)
>>> tuple({"name":"jason","age":18})			 # 结果:('name', 'age')
>>> tuple((1,2,3)) 					 # 结果:(1, 2, 3)
>>> tuple({1,2,3,4}) 					 # 结果:(1, 2, 3, 4)
# tuple()会跟for循环一样遍历出数据类型中包含的每一个元素然后放到元组中

3.基本使用

tuple1 = (1, 'hhaha', 15000.00, 11, 22, 33)

3.1 按索引取值(正向取+反向取):只能取,不能改否则报错!

>>> tuple1 = (1, 'hhaha', 15000.00, 11, 22, 33) 
# 1、按索引取值(正向取+反向取):只能取,不能改否则报错!  
>>> tuple1[0]
1
>>> tuple1[-2]
22
>>> tuple1[0] = 'hehe'  # 报错:TypeError:

3.2 切片(顾头不顾尾,步长)

>>> tuple1[0:6:2]
(1, 15000.0, 22)

3.3 长度

>>> len(tuple1)  
6

3.4 成员运算 in 和 not in

>>> 'hhaha' in tuple1 
True
>>> 'hhaha' not in tuple1  
False 

3.5 循环

>>> for line in tuple1:
...     print(line)
1
hhaha
15000.0
11
22
33
posted @ 2023-10-04 21:39  苙萨汗  阅读(5)  评论(0)    收藏  举报