1. 定义元组 如果只有一个元素 逗号不能省略
t0 = ()
print(type(t0))
t1 = (1,)
print(type(t1))
t2 = (1, True, False, "hello", [1, 2, 3], ("a", "b", "c"))
print(type(t2))
2. 使用两种方式都可以遍历元组, 方法类似字符串和列表
for e in (1, 2, 3, 4, 5, 6, 7, 8, 9):
print(e)
t3 = ("a", "b", "c", "d", "e")
for i in range(len(t3)):
print(i, t3[i])
3.元组是不可变类型 不能修改单个元素
object does not support item assignment
t4 = (1, 2, 3)
print(t4[0], t4[1], t4[len(t4)-1])
t4[0] = 100
object does not support item assignment
s = "hello"
s[0] = "a"
4.修改元组中的列表 不等于修改元组
t5 = (1, 2, 3, ["a", "b"], "hello")
print(type(t5[3]))
t5[3].append("c")
print(type(t5), t5[3])
5.count统计出现次数
print((1, 2, 3, 2, 1).count(3))
t = (1, 2, 3, 2, 1, 3)
value = 3
if value in t:
print(t.index(value, 3, 6))
t1 = ("a", "b", "c")
print(id(t1))
t2 = (1, 2, 3)
t1 = t1 + t2
print(id(t1)
print(t1, type(t1))
i0 = 100
print(i0)
i0 = 200
print(i0)
总结: