用Python解开元组
Python提供了称为元组的不可变数据类型。在本文中,我们将学习在Python3.x中打包一个拆包元组类型。或更早。
包装和拆装元组
Python提供了一个非常强大的元组分配工具,可将右侧参数映射到左侧参数。映射在一起的动作称为将值的元组拆包为norml变量。在打包时,我们通过常规赋值将值放入常规元组中。
现在让我们看一下它的实现-
示例
# Packing tuple varibles under one varible name tup = ("Nhooo", "Python", "Unpacking a tuple") # Packing tuple varibles into a group of arguments (website, language, topic) = tup # print college name print(website,"\t",language," ",topic)
输出结果
Nhooo Python Unpacking a tuple
在元组的拆包,对左侧的变量总数应相当于在给定的元组值的总数目和设定。
Python提供了语法以传递可选参数(*arguments)以进行任意长度的元组拆包。所有值将按照其指定顺序分配给每个变量,所有剩余值将分配给*arguments。让我们请看以下代码。
示例
# Packing tuple variables under one variable name tup = ("Nhooo", "Python","3.x.",":Data Structure","Unpacking a tuple") # Packing tuple variables into a group of arguments (website,*language, topic) = tup # print college name print(website,"\t",*language," ",topic)
输出结果
Nhooo Python 3.x. :Data Structure Unpacking a tuple
在python中,可以使用函数将元组解包,而在传递功能元组时,在函数中,值将其解包到普通变量中。以下代码说明了如何处理任意数量的参数。
“*_”用于指定元组中的任意数量的参数。
示例
# Packing tuple varibles under one varible name tup = ("Nhooo", "Python","3.x.","Data Structure:","Unpacking a tuple") # UnPacking tuple variables into a group of arguments and skipping unwanted arguments (website,*_,typ,topic) = tup # print college name print(website,"\t",typ," ",topic)
输出结果
Nhooo Data Structure: Unpacking a tuple
如果我们只想跳过一个参数,则可以将“*_”替换为“_”
结论
在本文中,我们学习了如何以多种方式打包和拆包元组。