36 lines
1.1 KiB
Python
36 lines
1.1 KiB
Python
|
||
# 可迭代对象分解
|
||
def iterable_breakdown(list):
|
||
# 如果可迭代对象长度大于接数据的变量数量,分解值过多报错
|
||
length = list.__len__()
|
||
length = 20
|
||
# 这样会报错,因为list长度是20,但分解变量只有两个
|
||
x, y = list
|
||
|
||
# 想要接住任意长度的列表,需要用*
|
||
# *x是包含list前n-1个元素的列表,y是最后一个元素
|
||
# 我们可以在任意位置接入带*的参数来接住一些值,这些值会在*变量中以列表存储
|
||
*x, y = list
|
||
x, *y, z = list
|
||
|
||
# 假设有一个变长元组序列
|
||
record = [("foo",1,2),("bar","suka"),("foo",2,4)]
|
||
|
||
def do_foo(x,y):
|
||
print(x,y)
|
||
|
||
def do_bar(s):
|
||
print(s)
|
||
|
||
# 我们可以使用*来解包从而将参数薅出来
|
||
for tag, *args in record:
|
||
if tag == "foo":
|
||
do_foo(*args)
|
||
elif tag == "bar":
|
||
do_bar(*args)
|
||
|
||
# 同理,也可以用*变量来占位挖掉不要的变量,比如在特定位置用*ignore或*_来挖掉参数
|
||
|
||
|
||
|
||
|