Files
Python_CookBook_repo/1.数据结构与算法/2.从任意可迭代对象中分解元素.py
2025-09-10 16:12:45 +08:00

36 lines
1.1 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 可迭代对象分解
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或*_来挖掉参数