tuple_basics.py 2.3 KB

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