目录

定义元组

元组的相关操作

修改元组

元组的删除

转换为元组tuple


定义元组

元组同列表一样,都是可以封装多个、不同类型的元素在内。
但最大的不同点在于:
元组一旦定义完成,就不可修改

元组定义:定义元组使用小括号,且使用逗号隔开各个数据,数据可以是不同的数据类型。

Python中列表嵌套元组取值 python元组嵌套元组_Python中列表嵌套元组取值

元组也支持嵌套:

t1=(1,"hello",False)
print(t1)
print(type(t1))

t11="a",1,True
print(t11)
print(type(t11))

t2=((1,2,3),[4,5,6])
print(t2[0][-1])
print(t2[1][0])

(1, 'hello', False)
<class 'tuple'>
('a', 1, True)
<class 'tuple'>
3
4

注意:元组只有一个数据,这个数据后面要添加逗号 

t1=("hello",)
t2=("hello")
print(t1)
print(type(t1))
print(t2)
print(type(t2))

 ('hello',)
<class 'tuple'>
hello
<class 'str'>

否则类型为字符串,而不是元组

元组的相关操作

 除了不可修改,元组与列表的操作几乎一模一样

Python中列表嵌套元组取值 python元组嵌套元组_ui_02

修改元组

元组中的元素值是 不允许修改 的,但我们可以对元组进行连接组合,如下实例:

my_tuple1=("hello",[1,2,3])
my_tuple2=(True,666)

t=my_tuple1+my_tuple2

print(t)

('hello', [1, 2, 3], True, 666) 

值得注意的是 :

不可以修改元组的内容,否则会直接报错

my_tuple=("hello",[1,2,3])
my_tuple[1]=[4,5,6]

Python中列表嵌套元组取值 python元组嵌套元组_元组_03

但可以修改元组内的list的内容(修改元素、增加、删除、反转等)

my_tuple=("hello",[1,2,3])

#my_tuple[1]=[4,5,6]

my_tuple[1][0]=True
print(my_tuple)

('hello', [True, 2, 3])

甚至可以提出来修改

my_tuple1=("hello",[1,2,3])

list_1=my_tuple1[1]
list_1[0]=666

print(my_tuple1)

('hello', [666, 2, 3])

元组的删除

不可用pop,只能用del全删

my_tuple1=("hello",[1,2,3])

#tmp=my_tuple1.pop(0)
del my_tuple1
print(my_tuple1)

报错:因为已经将my_tuple1连同名字都删了

Traceback (most recent call last):
   File "C:\顺序.py\y.py", line 5, in <module>
     print(my_tuple1)
 NameError: name 'my_tuple1' is not defined

转换为元组tuple

my_list = [1, 2, 3, 4, 5]
my_tuple = (1, 2, 3, 4, 5)
my_str = "abcdefg"
my_set = {1, 2, 3, 4, 5}
my_dict = {"key1": 1, "key2": 2, "key3": 3, "key4": 4, "key5": 5}

# 类型转换: 容器转元组
print(f"列表转元组的结果是:{tuple(my_list)}")
print(f"元组转元组的结果是:{tuple(my_tuple)}")
print(f"字符串转元组结果是:{tuple(my_str)}")
print(f"集合转元组的结果是:{tuple(my_set)}")
print(f"字典转元组的结果是:{tuple(my_dict)}")

 列表转元组的结果是:(1, 2, 3, 4, 5)
元组转元组的结果是:(1, 2, 3, 4, 5)
字符串转元组结果是:('a', 'b', 'c', 'd', 'e', 'f', 'g')
集合转元组的结果是:(1, 2, 3, 4, 5)
字典转元组的结果是:('key1', 'key2', 'key3', 'key4', 'key5')

总结:

经过上述对元组的学习,可以总结出列表有如下特点:

  1. 可以容纳多个数据
  2. 可以容纳不同类型的数据(混装)
  3. 数据是有序存储的(下标索引)
  4. 允许重复数据存在
  5. 不可以修改(增加或删除元素等)
  6. 支持for循环

多数特性和list一致,不同点在于不可修改的特性。

Python中列表嵌套元组取值 python元组嵌套元组_元组_04