首页 > 解决方案 > 分解以下代码的循环逻辑:

问题描述

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

我是拆包新手

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)

标签: pythoniterable-unpacking

解决方案


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)

我建议为了更好地理解,您可以阅读文档


推荐阅读