Python 这个列表索引怎么会超出范围?(斐波那契数)
此代码应打印斐波那契序列前十个数字中偶数的总和Python 这个列表索引怎么会超出范围?(斐波那契数),python,list,for-loop,range,Python,List,For Loop,Range,此代码应打印斐波那契序列前十个数字中偶数的总和 #Creates a list with the first ten Fibonacci numbers. l = [1,2] for i in range(10): l.append(l[i]+l[i+1]) for i in l: #If an element of the Fibonacci list is uneven, replace it with zero. if l[i]%2 != 0:
#Creates a list with the first ten Fibonacci numbers.
l = [1,2]
for i in range(10):
l.append(l[i]+l[i+1])
for i in l:
#If an element of the Fibonacci list is uneven, replace it with zero.
if l[i]%2 != 0:
l[i] = 0
#Print the sum of the list with all even Fibonacci numbers.
print sum(l)
当我执行此操作时,我得到:
File "pe2m.py", line 6, in <module>
if l[i]%2 != 0:
IndexError: list index out of range
我不明白它是如何超出范围的,有人能澄清一下吗?你的问题是l中的I:它不给你索引,它给你列表元素。由于元素是整数,它们可能是有效的,前几个元素也可能是有效的,但它们没有您想要的值-您必须再次在一个范围内进行迭代。您是在值上循环,而不是在索引位置上循环 请改用以下代码:
#Creates a list with the first ten Fibonacci numbers.
l = [1,2]
for i in range(10):
l.append(l[i]+l[i+1])
for i in range(len(l)):
#If an element of the Fibonacci list is uneven, replace it with zero.
if l[i]%2 != 0:
l[i] = 0
#Print the sum of the list with all even Fibonacci numbers.
print sum(l)
不能使用列表中的值为列表编制索引,因为不能保证该值在列表边界内 看到您的代码,我觉得您正计划执行以下操作
>>> for i,e in enumerate(l):
#If an element of the Fibonacci list is uneven, replace it with zero.
if e%2 != 0:
l[i] = 0
有趣的是,你可以像下面这样做。在看到GLGL的评论后编辑]
>>> print sum(e for e in l if e%2)
Python的for x in y构造返回x中序列的值/元素,而不是它们的索引
至于斐波那契数:序列从1,1开始,而不是1,2。可以这样简单地求和:
a, b = 1, 1
s = 0
for i in range(10):
a, b = b, a+b
if b % 2 = 0:
s += b
print s
如果需要获得前N个偶数的总和,可以执行以下操作:
a, b = 1, 1
s = 0
count = 0
while count < 10:
a, b = b, a+b
if b % 2 = 0:
s += b
count += 1
print s
或者,如果e%2,就用l表示e。谢谢,解释清楚!结果仍然不是我想要的,因为如果我只想要前十个数字,我必须做10-2的范围。
from itertools import islice
def fib():
a, b = 1, 1
yield a
yield b
while True:
a, b = b, a+b
yield b
even_sum = reduce(lambda x, y: x+y if y % 2 == 0 else x, islice(fib(), 10), 0)