我有以下字典,它是从 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
关于python - 为什么我收到错误 'exceptions.ValueError: too many values to unpack' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26445190/