Python中元组的学习

Python 的元组与列表类似,不同之处在于元组的元素不能修改

一、元组的声明

tup1 = ("python",1,"apple",[1,2,3])
print(tup1)

注意:元组中只包含一个元素时,需要在元素后面添加逗号

tup1 = ("python")
tup2 = ("python",)
print(type(tup1))   # <class 'str'>
print(type(tup2))   # <class 'tuple'>

二、元组的取值同字符串:元组[索引]

tup1 = ("python",1,"apple",[1,2,3])
print(tup1[1])  # 1
print(tup1[-1][1])  #2

三、往元组中增加元素:元组不支持修改,但可以通过连接组合的方式进行增加

tup1 = ("python",1,"apple",[1,2,3])
tup2 = ("hello",2)
tup3= tup1 + tup2 
print(tup3)  # ('python', 1, 'apple', [1, 2, 3], 'hello', 2)

四、元组的修改:元组是不可变类型,不能修改元组的元素。可通过现有的字符串拼接构造一个新元组

tup1 = ("python",1,"apple",[1,2,3])
tup1 = tup1[1:3]
print(tup1)  # (1, 'apple')

五、元组的删除:元组不支持单个元素删除,但可以删除整个元组

tup1 = ("python",1,"apple",[1,2,3])
del tup1
print(tup1)  # NameError: name 'tup1' is not defined
posted @ 2020-07-27 17:34  朵渔  阅读(212)  评论(0编辑  收藏  举报