一、介绍
1、使用元组的好处在于对元组进行操作更为高效,适合存放一组常量
2、Tuple 比 list 操作速度快
如果您定义了一个值的常量集, 并且唯一要用它做的是不断地遍历它。请使用 tuple 代替 list
3、dictionary keys 可以是字符串, 整数和 “其它几种类型”。Tuples就是这些类型之一。 Tuples 可以在 dictionary 中被用做 key 但是 list 不行。实际上,事情要比这更复杂。Dictionary key 必须是不可变的。Tuple本身是不可改变的, 但是如果您有一个list的tuple, 那就认为是可变的了,用做key就是不安全的。只有字符串, 整数或其它对 dictionary 安全的 tuple 才可以用作 dictionary key。
4、Tuple 是不可变 list,一旦创建了一个 tuple 就不能以任何方式改变它。
二、初始化
#tuple初始化
print("===="*5,"init")
tuple1 = (3,2,1)
list1 = [1,2,3]
print("tuple1:",tuple1)
print("list1:",list1)
tuple1 = ([1,2,3,'A','B','C'],4,'D')
list1 = ([1,2,3,'A','B','C'])
print("tuple1:",tuple1)
print("list1:",list1)
#tuple=====list相互转换
#如果对不需要修改的数据进行 “写保护”
#使用 tuple 而不是 list 如同拥有一个隐含的 assert 语句
#说明这一数据是常量。
#如果必须要改变这些值, 则需要执行 tuple 到 list 的转换 (需要使用一个特殊的函数)。
list2 = list(tuple1)
tuple2 = tuple(list1)
print("===="*5,"change")
print("tuple2:",tuple2)
print("list2:",list2)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
![]()
三、索引
#tuple 索引
print("===="*5,"index")
tuple1 = (1,2,3) #Tuple 固定的数组,一旦定义后,其元素个数是不能再改变的。
#tuple1.remove(1) 元组不能追加(append)元素,弹出(pop)元素等
#tuple1.append(4) 元组不能追加(append)元素,弹出(pop)元素等
print("tuple1[1]:",tuple1[1]) #只能对元组中的元素进行索引
#tuple1[1] = 100 不能对其中的元组进行赋值
- 1
- 2
- 3
- 4
- 5
- 6
- 7
![]()
四、添加
#元组的添加
print("===="*5,"add")
tuple1 = (1,2,3)
tuple2 = (4,5,6)
#不能直接改,但可与其他方法添加
tuple3 = tuple1 + tuple2
print("tuple3:",tuple3)
tuple4 = tuple1 + ('1',)
print("tuple4:",tuple4)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
![]()
五、删除
#删除元组
print("===="*5,"del")
tuple1 = (1,2,3)
del tuple1
- 1
- 2
- 3
- 4
六、遍历
#遍历查看(与列表一样)
print("===="*5,"for")
tuple1 = (1,2,3)
for v in tuple1:
print(v)
for i in range(len(tuple1)):
print ("index = %s,value = %s" % (i, tuple1[i]))
for i, v in enumerate(tuple1):
print ("index = %s,value = %s" % (i, v))
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
![]()
文章知识点与官方知识档案匹配,可进一步学习相关知识
Python入门技能树基础语法缩进规则416632 人正在系统学习中
评论记录:
回复评论: