分解以下代码的循环逻辑:

问题描述 投票:0回答:2

我试图理解下面的代码,但我无法得到循环部分

我是新手拆包

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)
python iterable-unpacking
2个回答
0
投票

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-loop tag, *args中,*args用于对齐 - 它将东西打包成元组。在函数调用中,*args用作参数 - 它将东西解包到函数调用参数中。


0
投票
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

© www.soinside.com 2019 - 2024. All rights reserved.