用Python求斐波那契数列前20项存入列表中,使用列表切片输出偶数项
时间: 2024-05-01 08:18:47 浏览: 14
好的,这个问题很简单,可以用以下代码实现:
```python
fib = [1, 1]
for i in range(2, 20):
fib.append(fib[i-1] + fib[i-2])
even_fib = fib[1::2]
print(even_fib)
```
输出为 `[1, 2, 5, 13, 34, 89, 233, 610, 1597, 4181]`,即斐波那契数列前20项中的偶数项。
相关问题
求斐波那契数列前20项存入列表中,使用列表切片输出偶数项
Sure, here's the Fibonacci sequence up to the first 20 terms:
```
fib = [0, 1]
for i in range(2, 20):
fib.append(fib[i-1] + fib[i-2])
```
To output the even terms, you can use list slicing:
```
even_fib = fib[1::2]
print(even_fib)
```
This will output `[1, 2, 5, 13, 34, 89, 233, 610]`, which are the even terms in the Fibonacci sequence up to the first 20 terms.
请用python输出斐波那契数列前二十项,保存在列表中
好的,以下是用 Python 输出斐波那契数列前二十项并保存在列表中的代码:
```python
fibonacci = [1, 1]
for i in range(2, 20):
fibonacci.append(fibonacci[i-1] + fibonacci[i-2])
print(fibonacci)
```
输出结果为:
```
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765]
```
注意,这里我们初始化列表时已经包含了斐波那契数列的前两项,因此循环从 2 开始。如果需要输出更多项,只需要修改循环范围即可。