元组的定义及常用方法:
"""
元祖:
元祖是一系列的数据的顺序组合,不可修改,增加,删除
是有序的
标识符:()
关键字:tuple
使用场景:格式化输出,保证安全性,函数的参数,函数的返回值
特点:如果只有1个元素,不加逗号,则不是元祖
元祖的常用方法:
+ : 元祖拼接
* : 重复输出
元祖只能做查询操作,不能做增删改的操作
查看单个元素: 元组名[索引值]
查看多个元素: 元组名[start,end,step]
元组的其他方法:
查看元组的索引值 tp.index(元素)
统计元素的格式 tp.count(元素)
数据类型转换:
str 可转 tuple
list 可转 tuple
tuple 可转 list
tuple 可转 str
"""
# 定义一个空元组
tp1 = ()
print(len(tp1))
# 只包含1个元素的元祖
tp2 = (1,)
print(type(tp2))
print(len(tp2)) # <class 'tuple'>
# 1个元素不加逗号就不是元祖
tp3 = (2)
print(type(tp3)) # <class 'int'>
tp1 = (1, 2, 'abc', True, False, 0)
tp2 = (3, 4)
# +
tp = tp1 + tp2
print(tp)
# *
tp = tp1 * 2
print(tp)
# 获取元素1
res = tp1[0]
# 获取1,2
res = tp1[0:2]
tp1 = (1, 2, 'abc', True, False, 0, [1, 2, 3], 'hello')
# 获取hello中的'o'
res = tp1[-1][-1]
print(res)
# 元组的其他方法
# 判断3是否在倒数第二个元素中?
print(3 in tp1[-2])
# 统计1的个数
print(tp1.count(1))
str1 = 'hello'
print(tuple(str1)) # ('h', 'e', 'l', 'l', 'o')
list1 = [1, 2, 3, 4]
print(tuple(list1)) # (1, 2, 3, 4)
tp1 = (1, 0, 3.14, True, False, ['a', 'b', 'c'], 'hello')
print(list(tp1)) # [1, 0, 3.14, True, False, ['a', 'b', 'c'], 'hello']
m = str(tp1)
print(m) # (1, 0, 3.14, True, False, ['a', 'b', 'c'], 'hello')
print(type(m)) # <class 'str'>