# 元组 tuple() # 定义 tu = () # 空元组 tu1 = (1, 2, 3) # 一旦初始化,不可再改变 # 索引 print(tu1[0]) # 1 print(tu1[-1]) # 3 # print(tu1[3]) # 报错 超出索引范围 # 切片 tu2 = (1, 2, 3, 4, 5) print(tu2[0:2]) # 不允许改变 ''' tu2[0] = 6 # TypeError: 'tuple' object does not support item assignment # 报错 类型错误,元组类型不支持字典中的项赋值 item : 列表中的元素、字典中的项或迭代器中的下一个元素 assignment : 赋值 ''' # 统计个数 tu2 = (1, 2, 3, 4, 5, 5, 5) # print(tu2.count()) # 0 ''' TypeError: tuple.count() takes exactly one argument (0 given) 类型错误 元组的计数count()功能需要精确地给出一个参数,现在给到0个 exactly 恰好 正好 精确地 完全准确地 ''' print(tu2.count(tu2)) # 0 print(tu2.count(6)) # 0 # 给到元组中不存在的元素作参数会返回0,不报错 # 正常用的方式: print(tu2.count(5)) # 3 # 索引 tu2 = (1, 2, 3, 4, 5, 5, 5) print(tu2.index(5)) # 4 跟列表中使用一样,返回元素5在元组中第一次出现的位置下标 # print(tu2.index(6)) # 报错 值错误,元素不在元组中 ValueError: tuple.index(x): x not in tuple # 可以遍历 for i in tu2: print(i) for i, n in enumerate(tu2): print(i, n) # 长度 print(len(tu2)) # + 合并 add tu1 = (1, 2, 3) tu2 = (4, 5, 6) print(tu1 + tu2) # (1, 2, 3, 4, 5, 6) # * mul tu1 = (1, 2, 3) print(tu1 * 4) # (1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3) # 能逆序和排序 ,非永久的排序/逆序 tu1 = (1, 2, 3) print(tuple(reversed(tu1))) # (3, 2, 1) tu1 = (1, 4, 3) print(tuple(sorted(tu1))) # (1, 3, 4) # max min sum print(max(tu1)) print(min(tu1)) print(sum(tu1))标签:count,tuple,tu1,tu2,预习,元组,print From: https://blog.csdn.net/m0_61566562/article/details/140407761