元组
python的元组与列表类似,不同之处在于元组的元素不能修改。元组使用小括号,列表使用方括号。创建的元组也可以不加括号,若元组中只包含一个元素,需要在元素后添加逗号,否则会被当做运算符使用。元组的访问与删除与列表的一致。
访问元组
tup1=('China','UK','USA','Australia','France','Japan')
tup2=(1,2,3,4,5,6)
print(tup1)
print(tup2)
print("tup1[0]:",tup1[0])
print("tup2[1:5]:",tup2[1:5])
"""
('China', 'UK', 'USA', 'Australia', 'France', 'Japan')
(1, 2, 3, 4, 5, 6)
tup1[0]: China
tup2[1:5]: (2, 3, 4, 5)
"""
修改元组
修改元组与修改列表不一样,不能从新给元组中的一个元素赋值。
tup1=('China','UK','USA','Australia','France','Japan')
tup2=(1,2,3,4,5,6)
print(tup1)
print(tup2)
print("tup1[0]:",tup1[0])
print("tup2[1:5]:",tup2[1:5])
tup3=tup1+tup2;
print(tup3)
"""
('China', 'UK', 'USA', 'Australia', 'France', 'Japan')
(1, 2, 3, 4, 5, 6)
tup1[0]: China
tup2[1:5]: (2, 3, 4, 5)
('China', 'UK', 'USA', 'Australia', 'France', 'Japan', 1, 2, 3, 4, 5, 6)
"""
删除元组
tup1=('China','UK','USA','Australia','France','Japan')
tup2=(1,2,3,4,5,6)
print("tup2:",tup2)
del tup2;
print("删除后的tup2:")
print(tup2)
"""
tup2: (1, 2, 3, 4, 5, 6)
删除后的tup2:
Traceback (most recent call last):
File "E:/学习/C#/Run/新建文件夹/元组.py", line 6, in <module>
print(tup2)
NameError: name 'tup2' is not defined
"""
元组运算符
tup1=('China','UK','USA','Australia','France','Japan')
tup2=(1,2,3,4,5,6)
print("tup1:",tup1)
print("tup2:",tup2)
a=len(tup1)
b=tup1+tup2
print(a)
print(b)
for x in (tup2):
print(x,end=" ")
"""
tup1: ('China', 'UK', 'USA', 'Australia', 'France', 'Japan')
tup2: (1, 2, 3, 4, 5, 6)
6
('China', 'UK', 'USA', 'Australia', 'France', 'Japan', 1, 2, 3, 4, 5, 6)
1 2 3 4 5 6
"""
元组索引,截取
tup1=('China','UK','USA','Australia','France','Japan')
tup2=(1,2,3,4,5,6)
print("tup1:",tup1)
print("tup2:",tup2)
a=tup1[2]
b=tup2[-2]
c=tup2[1:5]
print("tup1[2]:",a)
print("tup2[-2]:",b)
print("tup2[1:5]:",c)
"""
tup1: ('China', 'UK', 'USA', 'Australia', 'France', 'Japan')
tup2: (1, 2, 3, 4, 5, 6)
tup1[2]: USA
tup2[-2]: 5
tup2[1:5]: (2, 3, 4, 5)
"""
元组的内置函数
tup1=('China','UK','USA','Australia','France','Japan')
tup2=(1,2,3,4,5,6)
list=['Sat','Sun','Mon']
print("tup1:",tup1)
print("tup2:",tup2)
print("列表list:",list)
a=len(tup1)
b=len(tup2)
c=max(tup2)
tup3=tuple(list)
print("tup1的长度:",a)
print("tup2的长度:",b)
print("tup2中的最大值是:",c)
print("列表list转换为元组tup3:",tup3)
"""
tup1: ('China', 'UK', 'USA', 'Australia', 'France', 'Japan')
tup2: (1, 2, 3, 4, 5, 6)
列表list: ['Sat', 'Sun', 'Mon']
tup1的长度: 6
tup2的长度: 6
tup2中的最大值是: 6
列表list转换为元组tup3: ('Sat', 'Sun', 'Mon')
"""