元组
Python的元组与列表类似,不同之处在于元组的元素不能修改。元组使用小括号,列表使用方括号。
>>> aTuple = ('et',77,99.9) >>> aTuple ('et',77,99.9)
<1>访问元组
<2>修改元组
<3>count, index
index和count与字符串和列表中的用法相同
>>> a = ('a', 'b', 'c', 'a', 'b') >>> a.index('a', 1, 3) # 注意是左闭右开区间 Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: tuple.index(x): x not in tuple >>> a.index('a', 1, 4) 3 >>> a.count('b') 2 >>> a.count('d') 0
例子1:
# 元组和列表极其相似 # 列表是可变的数据类型 (增删改查) # 元组是不可变的数据类型 (查) # 都可以保存任意的数据类型 而且都是有序的(都支持下标索引 和 切片) """ 字符串 -> '' "" 三引号 列表 -> [] 元组 -> () """ # 01: 元组的定义 # 格式: 元组名 = (元素1, 元素2, ...) my_tuple = (123, True, "hello", 3.14) print(my_tuple)
例子2:
# 02: 定义一个特殊的元组 空元组 my_tuple = () # 等价 # my_tuple = tuple() print(len(my_tuple)) # # <class 'tuple'> print(type(my_tuple))
例子3:
# 03: 定义一个特殊的元组 有且只有一个元素 # 格式: 元组名 = (元素,) my_tuple = (3.14,) print(my_tuple) print(type(my_tuple))
例子4:
# 04: 查 (循环遍历 in not index count) my_tuple = (123, True, "hello", 3.14) # 循环遍历 # for for value in my_tuple: print(value)
while循环:
# 04: 查 (循环遍历 in not index count) my_tuple = (123, True, "hello", 3.14) # 循环遍历 i = 0 while i < len(my_tuple): value = my_tuple[i] print(value) i += 1
例子5:
# 04: 查 (循环遍历 in not index count) my_tuple = (123, True, "hello", 3.14) # in not in if 123 not in my_tuple: print("存在") else: print("不存在")
例子6:
# 04: 查 (循环遍历 in not index count) my_tuple = (123, True, "hello", 3.14) # index ret = my_tuple.index(True) print(ret)
例子7:
# 04: 查 (循环遍历 in not index count) my_tuple = (123, True, "hello", 3.14) # count count = my_tuple.count(3.14) print(count)
例子8:
# 05: 验证下元组是不可变的数据类型 my_tuple = (123, True, "hello", 3.14) # # 通过下标修改对应的元素值 my_tuple[2] = "world" print(my_tuple)
运行结果:
TypeError: 'tuple' object does not support item assignment
例子9:
# 06: 为什么python会提出元组类型? # 保证其数据安全 my_list = (True, 3.14, 123) # my_list[1] = 3.1415926
运行结果:
TypeError: 'tuple' object does not support item assignment
例子10:
# 07: 定义一个空的元组 # my_tuple = () # 等价于 my_tuple = tuple() print(my_tuple)
例子11:
# 08: 对一个变量进行了重新赋值 跟可变不可变没有一点关系 my_tuple = (1, 2, 3) my_tuple1 = (1, 2, 3, 4)