[英]python iterating over multiple values in for loop
我for value1, value2 in args
中有for value1, value2 in args
for 循環失敗了,我不知道為什么。
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)
(從而避免在切片元組時出現任何錯誤)。 那也沒有用。
args
是一個元組。 您只能一個一個地迭代元組:
for el in args[1:]:
# Do something...
您只能在特定情況下迭代多個項目,例如:
d = {'one': 1, 'two': 2}
for key, value in d.items():
# Do something...
字典的items
方法返回一個特殊的dict_items
對象,可以像這樣迭代。 你不能只用任何東西來做它,它甚至對元組沒有意義。
如果您想獲得更具體的信息,對象在迭代時的行為由它在其__iter__
方法中返回的迭代器以及該迭代器在其__next__
方法中返回的內容決定。 如果它只返回單個值,例如在元組中,那么您無法將其解包為多個值。 在上面的示例中, dict__items
在迭代時返回一個 2 項元組,因此可以解包。
解包序列中的項目要求序列中的每個項目都是一個可迭代的,它產生的項目數量與接收值的表達式所期望的項目數量相同。 您可以改為使用zip
函數在按奇數和偶數索引切片后將序列中的項目配對。
改變:
for required,completed in args[1:]:
到:
for required, completed in zip(args[1::2], args[2::2]):
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.