pyothon学习笔记2-元组

时间:2023-03-08 19:19:34
# 1.元组对象不可修改,元组中列表对象的对象可以修改
t = (1,2,[1,2,3])
t[2] = [1,2,3,4]
# 'tuple' object does not support item assignment
t[2].append(4)
# 此时t=(1, 2, [1, 2, 3, 4]) # 2.tuple()将序列或迭代器转化为元组
tuple([1,2,3])
# (1, 2, 3)
tuple('str')
# ('s', 't', 'r')
tuple(range(4))
# (0, 1, 2, 3) # 3.元组串联(仅当两个对象都是元组时可用)&复制
# 串联
(1,2)+(5)
# TypeError: can only concatenate tuple (not "int") to tuple
(1,2)+(5,)
# (1,2,5)
# 复制
(1,2)* 2
# (1, 2, 1, 2) # 4.拆分元组
a, b, d = (2 ,3, 4)
# 此时a=2 b=3 c=4
# 可以用来简单交换变量的值
a, b = 1, 2
a, b = b, a
# 此时a=2 b=1 # 5.tuple方法
a = (1,2,3,4,3,3,1)
a.count(3)
#
len(a)
#
min(a)
#
max(a)
# # 6.特殊元组
# 空元祖
()
# 单个元素元组,必须加逗号
(1,)