[英]Why am I getting the error 'exceptions.ValueError: too many values to unpack'?
我有以下字典,即從XHR請求生成的json對象,其中字典鍵由元組組成:
{(u'goal', u'corner', u'rightfoot'): 1, (u'goal', u'openplay', u'rightfoot'): 3, (u'miss',
u'corner', u'header'): 8, (u'goal', u'corner', u'header'): 1, (u'goal', u'openplay', u'leftfoot'): 2,
(u'miss', u'openplay', u'rightfoot'): 30, (u'miss', u'corner', u'rightfoot'): 2, (u'miss',
u'crossedfreekick', u'header'): 3, (u'goal', u'penalty', u'rightfoot'): 1, (u'miss', u'fastbreak',
u'rightfoot'): 2, (u'miss', u'crossedfreekick', u'rightfoot'): 3, (u'goal', u'openplay', u'header'):
1, (u'goal', u'crossedfreekick', u'rightfoot'): 1, (u'miss', u'openplay', u'header'): 2, (u'goal',
u'crossedfreekick', u'header'): 1, (u'miss', u'openplay', u'leftfoot'): 22, (u'miss',
u'directfreekick', u'rightfoot'): 1, (u'miss', u'crossedfreekick', u'leftfoot'): 1}
我正在使用以下代碼來有條件地求和以上字典中的值:
goal1 = {"'goal','openplay','leftfoot'", "'goal','openplay','rightfoot'", "'goal','openplay','header'", "'goal','openplay','otherbodypart'"}
regex1 = sum(int(value) for key, value in regex if key in goal1)
但是,這會產生以下錯誤消息:
regex1 = sum(int(value) for key, value in regex if key in goal1)
exceptions.ValueError: too many values to unpack
誰能向我解釋這是為什么和/或更正替代語法?
謝謝
regex1 = sum(int(value) for key, value in regex.items() if key in goal1)
您需要使用包含鍵和值的dict.items
,循環遍歷regex
,僅對鍵進行迭代,因此無法解壓鍵和值,從而導致錯誤。
這些鍵也是元組,因此您需要將這些鍵作為元組存儲在goal1
:
goal1 = {('goal','openplay','leftfoot'), ('goal','openplay','rightfoot'), ('goal','openplay','header'), ('goal','openplay','otherbodypart')}
print(regex1)
6
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.