Python|将整个列表解包到变量中
有时,在使用列表时,我们可能希望将列表的每个元素转换或解压缩为所需的变量。此问题可能发生在 Web 开发领域。让我们讨论一些可以解决这个问题的方法。
方法#1:使用"=" operator
可以使用“=”运算符执行此任务。在这种情况下,我们只需确保足够的变量作为列表元素的计数并将它们分配给列表,列表元素按照它们的分配顺序分配给变量。
# Python3 code to demonstrate working of
# Unpack whole list into variables
# using "=" operator
# initialize list
test_list = [1, 3, 7, 4, 2]
# printing original list
print("The original list is : " + str(test_list))
# Unpack whole list into variables
# using "=" operator
one, two, three, four, five = test_list
# printing result
print("Variables as assigned are : " + str(one) + " "
+ str(two) + " "
+ str(three) + " "
+ str(four) + " "
+ str(five))
输出 :
The original list is : [1, 3, 7, 4, 2]
Variables as assigned are : 1 3 7 4 2
方法#2:使用命名元组
这个问题可以使用命名元组来解决,它可以存储具有变量名的列表元素,该变量名可以通过使用点运算符访问,并成功初始化变量名。
# Python3 code to demonstrate working of
# Unpack whole list into variables
# using Namedtuple
from collections import namedtuple
# initialize list
test_list = [1, 3, 7, 4, 2]
# printing original list
print("The original list is : " + str(test_list))
# Unpack whole list into variables
# using Namedtuple
temp = namedtuple("temp", "one two three four five")
res = temp(*test_list)
# printing result
print("Variables as assigned are : " + str(res.one) + " "
+ str(res.two) + " "
+ str(res.three) + " "
+ str(res.four) + " "
+ str(res.five))
输出 :
The original list is : [1, 3, 7, 4, 2]
Variables as assigned are : 1 3 7 4 2