解决方案可能相当简单,但我无法弄清楚.这是代码,它是一个简单的斐波那契数字生成器.目标是总结所有甚至斐波那契数字低于4,000,000.
我的方法是首先生成低于4,000,000的所有斐波纳契数,然后:
a)用偶数生成一个新列表(“偶数”)(这很好)
b)从列表中删除奇数“全部”
但是,在后一种情况下,由于我不明白的原因,输出是:
[2,5,5,21,34,89,144,377,610,1597,2584,6765,10946,28657,46368,121393,196418,514229,832040,2178309,3524578]
任何帮助深表感谢.谢谢!
all = []
even = []
def fibonacci():
a, b = 1, 2
while a < 4000000:
all.append(a)
a, b = b, a + b
print all
##Putting all the even fibonacci numbers in a different list and summing them up works fine
# for i in all:
# if i % 2 == 0:
# even.append(i)
# print even
# print sum(even)
# But for some strange reason I can't figure out how to remove the odd numbers from the list
for i in all:
if i % 2 != 0:
all.remove(i)
print all
print sum(all)
fibonacci()
解决方法:
这是一个“陷阱”情况:您在迭代列表时从列表中删除项目,从而更改列表,导致迭代行为异常.试试这个:
...
# But for some strange reason I can't figure out how to remove the odd numbers from the list
for i in all[:]:
if i % 2 != 0:
all.remove(i)
...
这就是所谓的“切片”表示法,并使您迭代列表的一次性副本,以便您的迭代不受all.remove()调用的影响.