使用Python 2.75在Euler prob 2中输出偶数Fibonacci数的列表

时间:2013-06-25 17:07:24

标签: python list python-2.x fibonacci

如何在Python 2.75上以列表形式输出结果(不用手动编写代码)。 而不仅仅是求解我插入print i的总和,然后求和并得到数字(其中11个)。请帮助解决这个非常基本的问题。谢谢。

##Even Fibonacci numbers Problem 2
##Each new term in the Fibonacci sequence is generated by adding the previous two terms.
##By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55...
##By considering the terms in the Fibonacci sequence whose values do not exceed
##four million, find the sum of the even-valued terms.
import fibo
sum = 0
a = fibo.fib2(4000000)
for i in a:
    if i%2==0:
        print i
        sum += i
print "the sum of these even Fibonacci numbers = "
print sum
###how to create list or tuple of the
##even_fib=[2, 8, 34, 144, 610, 2584, 10946, 46368, 196418, 832040, 3524578]

1 个答案:

答案 0 :(得分:1)

从一个空列表开始,当你发现它们将它们附加到:

even_fib = []

for i in a:
    if i %2 == 0:
        even_fib.append(i)

结果将是所有偶数元素的列表