解决方案可能相当简单,但我就是想不出来。这是代码,它是一个简单的斐波那契数生成器。目标是求和所有低于 4,000,000 的偶数斐波那契数。
我的方法是首先生成所有低于 4,000,000 的斐波那契数,然后: a)用偶数生成一个新列表(“偶数”)(这很好用) b) 从列表“all”中删除奇数
但是,在后一种情况下,由于我不明白的原因,输出是这样的: [2, 5, 8, 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() 调用的影响。
关于Python:模运算符的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9688983/