📜  在Python中解压元组

📅  最后修改于: 2022-05-13 01:54:56.193000             🧑  作者: Mango

在Python中解压元组

Python元组在Python中,元组用于存储不可变对象。除了某些情况外, Python元组与列表非常相似。 Python元组是不可变的,意味着它们不能在整个程序中被修改。

打包和解包元组:在Python中,有一个非常强大的元组分配功能,可以将值的右侧分配到左侧。在另一种方式中,它被称为将值元组解包到变量中。在打包过程中,我们将值放入一个新的元组中,而在解包过程中,我们将这些值提取到一个变量中。

示例 1

Python3
# Program to understand about
# packing and unpacking in Python
 
# this lines PACKS values
# into variable a
a = ("MNNIT Allahabad", 5000, "Engineering") 
 
# this lines UNPACKS values
# of variable a
(college, student, type_ofcollege) = a 
 
# print college name
print(college)
 
# print no of student
print(student)
 
# print type of college
print(type_ofcollege)


Python3
# Python3 code to study about
# unpacking python tuple using *
 
# first and last will be assigned to x and z
# remaining will be assigned to y
x, *y, z = (10, "Geeks ", " for ", "Geeks ", 50)
 
# print details
print(x)
print(y)
print(z)
 
# first and second will be assigned to x and y
# remaining will be assigned to z
x, y, *z = (10, "Geeks ", " for ", "Geeks ", 50)
print(x)
print(y)
print(z)


Python3
# Python3 code to study about
# unpacking python tuple using function
 
# function takes normal arguments
# and multiply them
def result(x, y):
    return x * y
# function with normal variables
print (result(10, 100))
 
# A tuple is created
z = (10, 100)
 
# Tuple is passed
# function unpacked them
 
print (result(*z))


输出:
MNNIT Allahabad
5000
Engineering

注意:在解包元组时,左侧的变量数应等于给定元组 a 中的值数。
Python使用一种特殊的语法来传递可选参数 (*args) 以进行元组解包。这意味着在Python中可以有许多参数代替 (*args) 。所有值都将分配给左侧的每个变量,所有剩余值将分配给 *args 。为了更好地理解,请考虑以下代码。

示例 2

Python3

# Python3 code to study about
# unpacking python tuple using *
 
# first and last will be assigned to x and z
# remaining will be assigned to y
x, *y, z = (10, "Geeks ", " for ", "Geeks ", 50)
 
# print details
print(x)
print(y)
print(z)
 
# first and second will be assigned to x and y
# remaining will be assigned to z
x, y, *z = (10, "Geeks ", " for ", "Geeks ", 50)
print(x)
print(y)
print(z)
输出:
10
['Geeks ', ' for ', 'Geeks ']
50
10
Geeks 
[' for ', 'Geeks ', 50]

在Python中,可以使用函数中的函数来解压缩元组,传递函数元组并将函数中的值解压缩到普通变量中。请考虑以下代码以更好地理解。

示例 3:

Python3

# Python3 code to study about
# unpacking python tuple using function
 
# function takes normal arguments
# and multiply them
def result(x, y):
    return x * y
# function with normal variables
print (result(10, 100))
 
# A tuple is created
z = (10, 100)
 
# Tuple is passed
# function unpacked them
 
print (result(*z))
输出:
1000
1000