基本数据类型之元组

元组

用途:存储多个不同类型的值(不能存可变类型)

定义方式:用小括号存储数据,数据之间通过逗号分隔(值不能被改变)

t1 = ('a','b') # t1 = tuple(('a','b'))

强调:如果元组内只有一个值,则必须加一个逗号
常用方法:

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

# 2、切片(顾头不顾尾,步长)
tuple1[0:6:2] 
>>> (1, 15000.0, 22)

# 3、长度
len(tuple1)  
>>> 6

# 4、成员运算 in 和 not in
tuple1 = (1, 'hhaha', 15000.00, 11, 22, 33)
print('hhaha' in tuple1)
print('hhaha' not in tuple1)

# 5、count()
tuple1 = (1, 'hhaha', 15000.00, 11, 22, 33)
print(tuple1.count(11))
>>>1
# 6、index()
tuple1 = (1, 'hhaha', 15000.00, 11, 22, 33)
print(tuple1.index('hhaha'))
>>>1

猜你喜欢

转载自www.cnblogs.com/baohanblog/p/11807413.html