选自 《python cookbook》
利用*表达式分解可迭代对象,无需复杂操作即可得到相关元素。
# 以下是*表达式在一个变长的元组序列中拆分出tag后的相关元素
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2024/7/14 下午8:33
# @Author : s
records = [
('foo', 1, 2),
('bar', 'hello'),
('foo', 3, 4)
]
def do_foo(x, y):
print('foo', x, y)
def do_bar(s):
print('bar', s)
for tag, *args in records:
if tag == 'foo':
do_foo(*args)
if tag == 'bar':
do_bar(*args)
网友评论