ループのために複数の値を反復パイソン

クリスティーナ周:

たループのための私の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)(これタプルをスライスして、エラーを回避します)。それはまた、動作しませんでした。

chuck2002:

argsタプルです。あなたは一つだけでタプル1を反復処理することができます:

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

あなたは、例えば、唯一のceratin状況下で複数の項目を反復処理することができます。

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

items辞書戻る方法特別なdict_itemsそのような反復処理することができるオブジェクト。あなたはただそれもタプルのために意味がありません、何でそれを行うことはできません。

あなたはより具体的に取得したい場合は、それが繰り返し処理されていたオブジェクトの振る舞いは、その中で返すイテレータによって決定される__iter__方法、およびどのようなその中のイテレータを返すこと__next__方法。それだけでタプルのように、単一の値を返す場合は、いくつかの値にそれを解凍することはできません。上記の例では、dict__items上繰り返し、従って解凍することができる場合に2項目タプルを返します。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=23807&siteId=1