python - 分解以下代码的循环逻辑:
问题描述
我试图理解下面的代码,但我无法获得循环部分
我是拆包新手
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)
elif tag == 'bar':
do_bar(*args)
解决方案
records = [('foo',1,2),('bar','hello'),('foo',3,4)]
def do_foo(x,y):
#This function takes two arguments
print('foo',x,y)
def do_bar(s):
#This function takes one argument
print('bar',s)
for tag, *args in records:
#Here we are looping over the list of tuples.
#This tuple can have 2 or 3 elements
#While looping we are getting the first element of tuple in tag,
# and packing rest in args which can have 2 or 3 elements
if tag == 'foo':
#do_foo requires 2 arguments and when the first element is foo,
# as per the provided list tuple is guaranteed to have total 3 elements,
# so rest of the two elements are packed in args and passed to do_foo
do_foo(*args)
elif tag == 'bar':
#Similarly for do_bar
do_bar(*args)
我建议为了更好地理解,您可以阅读文档。
推荐阅读
- qt - `QKeySequence::match()` 什么时候返回 `QKeySequence::PartialMatch`?
- python - 使用 smote 时出现此错误
- c# - 如何在 Angular 中记录 Http 通信错误
- javascript - JavaScript 将原始数组保留在递归函数中
- python - Python,Pandas 替换数据
- replace - 如何删除指定字符之前的一行中的所有字符
- javascript - React TS - 类型 '() => Promise
' 不可分配给类型 'EventHandler ' - java - loggerContext 的编程初始化和重新配置不使用文件源,而是使用我自己的包含 xml 配置的字符串
- javascript - 为什么获取查询总是返回错误段?
- amazon-web-services - 如何在 Amazon AppStream 2.0 上启用 Android Studio 调试