"""tuple_basics.py - Python 元组基础示例 一句话总结:元组就是“固定、稳定、不可修改的一组数据”。 包含常见的元组操作示例:创建、访问、切片、拼接、查找、解包、不可变性等。 运行后会打印每个示例的结果,并在代码中注释预期输出。 """ def main(): # 1. 创建元组 nums = (1, 2, 3, 4) names = ("alice", "bob", "charlie") mixed = (10, "python", True, 3.14) empty = () single = (42,) # 只有一个元素时必须保留逗号 print("nums ->", nums) print("names ->", names) print("mixed ->", mixed) print("empty ->", empty) print("single ->", single) # 2. 访问元素 print("nums[0] ->", nums[0]) # 1 print("nums[-1] ->", nums[-1]) # 4 print("names[1] ->", names[1]) # bob # 3. 切片 print("nums[1:3] ->", nums[1:3]) # (2, 3) print("names[:2] ->", names[:2]) # ('alice', 'bob') print("nums[::-1] ->", nums[::-1]) # 反转,返回新元组 # 4. 长度和成员判断 print("len(nums) ->", len(nums)) print("2 in nums ->", 2 in nums) print("5 in nums ->", 5 in nums) # 5. 计数和查找 numbers = (1, 2, 2, 3, 2, 4) print("numbers.count(2) ->", numbers.count(2)) # 3 print("numbers.index(3) ->", numbers.index(3)) # 3 # 6. 拼接 print("nums + (5, 6) ->", nums + (5, 6)) # 7. 元组不可变:不能修改元素 # 如果取消下面注释,会报错:TypeError # nums[0] = 100 # 8. 多重赋值(解包) student = ("Tom", 18, "CS") name, age, major = student print("unpack ->", name, age, major) # 9. 部分解包(*) first, *rest, last = (10, 20, 30, 40, 50) print("first, *rest, last ->", first, rest, last) # 10. 迭代 for item in names: print("loop ->", item) # 11. 元组常用于固定数据 point = (10, 20) x, y = point print("point = (10, 20), x, y ->", x, y) # 12. 与列表区别 # 列表可以修改,元组不能修改 list_example = [1, 2, 3] tuple_example = (1, 2, 3) list_example[0] = 100 print("list_example after change ->", list_example) # tuple_example[0] = 100 # 会报错,元组不可变 if __name__ == '__main__': main()