元组的声明
>>> (1,2) #使用逗号和括号声明
(1, 2)
>>> 1,2 #括号可省略
(1, 2)
>>> x = (40,) #声明只含一个元素的元组
>>> x
(40,)
>>> x = 40, #括号同样可省略
>>> x
(40,)
>>> len(x)
1
>>> (1,2)+(3,4) #元组合并
(1, 2, 3, 4)
x,y = y,x实现机制为元组
>>> x,y = 1,2
>>> x #单个变量
1
>>> y #单个变量
2
>>> x,y = y,x #Python交换变量(不需要临时变量,内部其实是元组)
>>> x
2
>>> y
1
>>> t = (1,2,3,4,5)
>>> t[0]
1
元组属于‘不可变’类型
>>> t[0] = 9 #元组不支持改变某一项的值
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
t[0] = 9
TypeError: 'tuple' object does not support item assignment
元组支持推导
>>> for x in t: #元组支持推导
print(x**2)
1
4
9
16
25
>>> res = [] #将元组的值的计算结果放入列表
>>> for x in t: #使用for循环
res.append(x**2)
>>> res
[1, 4, 9, 16, 25]
>>> res = [x**2 for x in t] #使用推导
>>> res
[1, 4, 9, 16, 25]
具名元组namedtuple
>>> from collections import namedtuple
>>> Emplyee = namedtuple('Emplyee',['name','age','department','salary']) #定义一个模板
>>> jerry = Emplyee('Jerry', age = 30, department = '财务部', salary = 9000.00)
>>> jerry.salary
9000.0
来源:CSDN
作者:Z_Kai_
链接:https://blog.csdn.net/qq_36536933/article/details/103860702