python在for循环中迭代多个值

2024-05-02 04:58:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我的for循环有for value1, value2 in args失败了,我不知道为什么

def school_completion(*args):
    """
    If any of the subjects have one or more incomplete testlet, the whole school is
    incomplete.

    :param args: tuple of 7 strs
        Should come as:
        (Eligible Students,
        ELA Required,
        ELA Completed,
        Math Required,
        Math Completed,
        Science Required,
        Science Completed)
    :return: str
    """
    # If there are no eligible students, return a dash.
    if args[0] == '0':
        return '-'

    # Set a boolean trigger.
    complete = True

    # Check for each subject pair.
    for required,completed in args[1:]:
        if required != completed:
            complete = False

    return 'Complete' if complete else 'Follow Up'

school_completion('1','6','6','7','7','8','8')

这给了我一个错误ValueError: not enough values to unpack (expected 2, got 1),似乎发生在for required,completed in args[1:]

我还尝试让我的函数接受(arg, *args)(从而避免了切分元组时的任何错误)。那也没用


Tags: oftheinforreturnifrequiredargs
2条回答

在序列中解包项要求序列中的每个项都是一个iterable,它生成的项数与接收值的表达式所期望的项数相同。您可以使用zip函数在按奇数和偶数索引对序列中的项进行切片后,对它们进行配对

更改:

for required,completed in args[1:]:

致:

for required, completed in zip(args[1::2], args[2::2]):

args是一个元组。只能逐个迭代元组:

for el in args[1:]:
   # Do something...

您只能在ceratin环境下迭代多个项目,例如:

d = {'one': 1, 'two': 2}
for key, value in d.items():
    # Do something...

dictionary的items方法返回一个特殊的dict_items对象,可以像这样进行迭代。你不能只处理任何东西,它甚至对元组都没有意义

如果您想更具体地说,对象在被迭代时的行为由它在__iter__方法中返回的迭代器以及该迭代器在__next__方法中返回的内容决定。如果它只返回一个值,如元组中的值,则无法将其解压为多个值。在上面的示例中,dict__items在迭代时返回一个2项元组,因此可以解包

相关问题 更多 >