# 定义元组
t0 = ()
print(type(t0))
# 运行结果 <class 'tuple'>
# 小括号在运算符里面属于优先级,所以运行结果还是一个整数,也就是1
t1 = (1)
print(type(t1))
# 运行结果 <class 'int'>
# 定义元组,如果只有一个元素逗号不能省略
t1 = (1,)
print(type(t1))
# 运行结果 <class 'tuple'>
# 元组中可以放入任何元素
t2 = (1,2,3,True,"hello",[1,2,3],("a","b","c"))
print(type(t2))
# 运行结果 <class 'tuple'>
# 遍历
for e in (1,2,3,4,5,6,7):
print(e)
# 运行结果:
# 1
# 2
# 3
# 4
# 5
# 6
# 7
t3 = ("a","b","c","d","e")
for i in range(len(t3)):
print(i,t3[i])
# 运行结果:
# 0 a
# 1 b
# 2 c
# 3 d
# 4 e
# 是不可变类型 不能修改单个元素
t4 = (1,2,3)
print(t4[0], t4[1], t4[len(t4) - 1])
# 运行结果:1 2 3
# t4 = (1,2,3)
# print(t4[0], t4[1], t4[len(t4) - 1])
# # 运行结果:1 2 3
# t4[0] = 100
# #运行结果: TypeError: 'tuple' object does not support item assignment
s = "hello"
s[0] = "a"
# 运行结果 TypeError: 'str' object does not support item assignment
python中存放列表,该列表仍然可以正常更改
t5 = (1,2,3,["a","b"])
# print(type(t5[3]))
t5[3].append("c")
print(type(t5),t5[3])
# 运行结果 <class 'tuple'> ['a', 'b', 'c']
统计出现次数
print((1, 2, 3, 3, 4).count(3))
# 运行结果 2
根据元素找索引,找不到就报错
print((1, 2, 3, 4, 5, 1).index(3)) # 找的小标索引为3的数,这个数是2
# 运行结果 2
t = (1,2,3,2,3,1)
#索引 0 1 2 3 4 5
value = 2 # 当value= 2 时,在索引3-6范围内,2的索引为3
if value in t:
print(t.index(value,3,6))
两个元组相加
t1 = ("a","b","c")
t2 = (1,2,3)
t1 = t1 + t2
print(t1,type(t1))
# 运行结果:('a', 'b', 'c', 1, 2, 3) <class 'tuple'>