前言
tuple作为不可变对象,每个tuple对象在第一次创建后,持有的元素不能改变,这是元组的基本概念,而元组解包功能是其中一个很常见的技术点,今天一起学习元组解包常用的3种情况
第一种:赋值给多个变量的元组解包
temp = ("hi","yuan","wai")
first,second,third = temp
等同于
temp = ("hi","yuan","wai")
first = temp[0]
second = temp[1]
third = temp[2]
说明:元组会自动解包,每个元素赋值给多个变量
注意:元素数量需要与变量数量相同
第二种:元组的每个元素作为位置参数的元组解包
temp = (1,2,3)
def hello(first,second,third):
print(first)
print(second)
print(third)
hello(*temp)
等同于
hello(1,2,3)
第三种:遍历的元素为元组对象时,同时赋值给对应的变量,自动完成元素解包
temp_list = [
('测试人员', self.tester),
('开始时间', start_time),
('合计耗时', duration),
('测试结果', status + ",通过率= " + self.pass_rate)]
for first, second in temp_list:
print(first)
print(second)
temp_list是一个list,每个元素为tuple,遍历temp_list时,将每次的获取到tuple对象,自动解包到2个变量first和second