您的位置:

Python 程序:解包元组项目

编写一个 Python 程序来解包元组项。通过将每个元组项分配给一个变量,我们可以解包元组项。这里,我们将四个元组项分配给四个不同的变量。

# Unpack Tuple Items

emp = ("John", 22, "Developer", 45000)
print(emp)

name, age, profession, sal = emp
print(name)
print(age)
print(profession)
print(sal)

通过使用,我们可以将多个解包的元组项分配给一个变量。例如,name,age,sal = emp 解包 emp 元组,并将 name 指定为 John,sal 指定为 45000,并将所有剩余的元组项指定为 age。

# Unpack Tuple Items

emp = ("John", "Root", 22, "Developer", 45000)
print(emp)

name, *age, sal = emp
print(name)
print(age)
print(sal)

print("==========")
name, age, *sal = emp
print(name)
print(age)
print(sal)

print("==========")
*name, age, prof, sal = emp
print(name)
print(age)
print(prof)
print(sal)

Python 元组解包输出

('John', 'Root', 22, 'Developer', 45000)
John
['Root', 22, 'Developer']
45000
==========
John
Root
[22, 'Developer', 45000]
==========
['John', 'Root']
22
Developer
45000