分解以下代码的循环逻辑:
Breaking down the loop logic for the below code:
我试图理解下面的代码,但我无法获得循环部分
我是开箱新手
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)
我建议为了更好地理解,你可以阅读documentation。
records
是一个元组 -> ('foo', 1, 2)
那里的for循环使用了多个迭代变量tag, *args
。这意味着元组被解包 - 即扩展为其成分。
tag
-> 从这个元组中请求一个元素,它得到 foo
.
*args
-> 请求元组中的所有其余元素 - 作为元组。它得到 (1,2)
:这是包装
现在do_foo(x,y)
是一个正常的功能。它被这样称呼 do_foo(*args)
。
请记住 args
现在是 (1,2)
。
*args
-> *(1,2)
-> 1,2
:元组被解包 - 由于 *
。表达式最终是 do_foo(1,2)
- 这符合我们的函数签名!
总而言之,在 for 循环 tag, *args
中,*args
用于赋值 - 将内容打包到一个元组中。在函数调用中, *args
用作参数 - 将内容解包到函数调用参数中。
我试图理解下面的代码,但我无法获得循环部分
我是开箱新手
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)
我建议为了更好地理解,你可以阅读documentation。
records
是一个元组 -> ('foo', 1, 2)
那里的for循环使用了多个迭代变量tag, *args
。这意味着元组被解包 - 即扩展为其成分。
tag
-> 从这个元组中请求一个元素,它得到 foo
.
*args
-> 请求元组中的所有其余元素 - 作为元组。它得到 (1,2)
:这是包装
现在do_foo(x,y)
是一个正常的功能。它被这样称呼 do_foo(*args)
。
请记住 args
现在是 (1,2)
。
*args
-> *(1,2)
-> 1,2
:元组被解包 - 由于 *
。表达式最终是 do_foo(1,2)
- 这符合我们的函数签名!
总而言之,在 for 循环 tag, *args
中,*args
用于赋值 - 将内容打包到一个元组中。在函数调用中, *args
用作参数 - 将内容解包到函数调用参数中。