摘要:在本节中,你将学习如何在 Python 中拆包(拆分、解包、解压)列表,以使你的代码更加简洁。
列表拆包介绍
colors = ['red', 'blue', 'green']
若要将列表的第一个、第二个和第三个元素赋值给变量,你可以像这样将各个元素赋值给变量:
colors = ['red', 'blue', 'green']
red = colors[0]
blue = colors[1]
green = colors[2]
然而,Python 提供了一种更好的方法来实现这一点。这被称为序列拆包。
基本上,你可以将列表(以及元组)中的元素赋值给多个变量。例如:
colors = ['red', 'blue', 'green']
red, blue, green = colors
print(red)
print(green)
print(blue)
此语句将 colors
列表的第一个、第二个和第三个元素分别赋值给 red
、blue
和 green
变量。
在此示例中,左侧的变量数量与右侧列表中的元素数量相同。
如果左侧使用的变量数量较少,则会引发错误。例如:
colors = ['red', 'blue', 'green']
red, blue = colors
错误:
ValueError: too many values to unpack (expected 2)
在这种情况下,Python 无法将三个元素拆包到两个变量中。
拆包与打包
如果你想要拆包列表中的前几个元素,并且不关心其他元素,你可以:
首先,将需要的元素拆包到变量中。
其次,将剩余的元素打包到一个新列表中,并将其赋值给另一个变量。
通过在变量名前放置星号(*
),你可以将剩余的元素打包到一个列表中,并将它们赋值给一个变量。例如:
colors = ['red', 'blue', 'green']
red, blue, *other = colors
print(red)
print(blue)
print(other)
输出:
red
blue
['green']
此示例将 colors
列表的第一个和第二个元素分别赋值给变量 red
和 green
。并且将该列表的最后一个元素赋值给变量 other
。
下面再举一个例子:
colors = ['cyan', 'magenta', 'yellow', 'black']
cyan, magenta, *other = colors
print(cyan)
print(magenta)
print(other)
输出:
cyan
magenta
['yellow', 'black']
此示例将前两个元素赋值给变量。它将最后两个元素打包到一个新列表中,并将该新列表赋值给变量 other
。
总结
拆包(unpacking)是将列表中的元素赋值给多个变量。
在变量名前使用星号(
*
),例如*变量名
,可以将列表中剩余的元素打包到另一个列表中。