Python 为什么 KeyError: 0
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23967788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why KeyError: 0
提问by mistermarko
I'm attempting to solve Project Euler 21 but I'm getting KeyError: 0 which normally occurs when you refer to a dictionary key that doesn't exist. However, I thought I had solved that problem with the < 10000 condition. The error refers to the first 'if' statement in the main() function.
我正在尝试解决 Project Euler 21,但我收到 KeyError: 0 这通常发生在您引用不存在的字典键时。但是,我认为我已经用 < 10000 条件解决了这个问题。该错误指的是 main() 函数中的第一个“if”语句。
sumsdivs = {}
for i in range(1, 10000):
tmpls = []
for j in range(1, i):
if i % j == 0:
tmpls.append(j)
sumsdivs[i] = sum(tmpls)
amls = []
def main():
for i in range(1, 10000):
if sumsdivs[i] < 10000 and sumsdivs[i] == sumsdivs[sumsdivs[i]]:
if sumsdivs[i] not in amls:
amls.append(sumsdivs[i])
if sumsdivs[sumsdivs[i]] not in amls:
amls.append(sumsdivs[sumsdivs[i]])
return sum(amls)
print(main())
Any ideas?
有任何想法吗?
回答by Martijn Pieters
You insert 0
for i = 1
here:
你0
在i = 1
这里插入:
sumsdivs = {}
for i in range(1, 10000):
tmpls = []
for j in range(1, i):
if i % j == 0:
tmpls.append(j)
sumsdivs[i] = sum(tmpls)
The inner loop never runs (range(1, 1)
is empty), and sum([])
is 0.
内部循环从不运行(range(1, 1)
为空),并且sum([])
为 0。
Demo:
演示:
>>> sumsdivs = {}
>>> for i in range(1, 2):
... tmpls = []
... for j in range(1, i):
... if i % j == 0:
... tmpls.append(j)
... sumsdivs[i] = sum(tmpls)
...
>>> sumsdivs
{1: 0}
>>> sum([])
0
So sumsdivs[1]
is 0, and sumsdivs[sumsdivs[0]]
throws a KeyError
:
sumsdivs[1]
0也是如此,并sumsdivs[sumsdivs[0]]
抛出一个KeyError
:
>>> sumsdivs[sumsdivs[1]]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 0