在python3中发布一个列表

2024-09-30 22:21:52 发布

您现在位置:Python中文网/ 问答频道 /正文

def fib2(n): #return Fibonacci series up to n
     """Return a list containing the Fibonacci series up to n."""
     result = []
     a, b = 0, 1
     while b < n:
          result.append(b) #see below
          a, b = b, a+b
     return result

#===========================================
f35 = fib2(35)     #call it
print (f35)        #write the result

好吧,这就是我目前的情况。给出了输出[1,1,2,3,5,8,13,21,34]。很好,但我需要倒过来。显示[34,21,13,8,5,3,2,1,1]。我只是不知道如何应用反向命令或使用[::-1]方法。你知道吗

如果我尝试应用上面的任何一种方法,我总是会遇到很多错误。我对这个很陌生。谢谢你抽出时间。你知道吗


Tags: theto方法returndefresultlistfibonacci
3条回答

试试这个

print (f35[::-1]) // Reversed list will be printed  

some other ways可以反转列表。所有这些都能用。你知道吗

也可以使用list对象的reverse方法

f35.reverse()
print(f35)

你可以用任何一个

return result[::-1] # or list(reversed(result))

或者

f35 = fib2(35)
f35.reverse()
print(f35)

作为一种替代方法,您可以使用insert而不是append来首先以正确的顺序构建列表?你知道吗

所以不是:

result.append(b)

执行:

result.insert(0, b)

它将b放在列表的索引0处,并将所有其他元素推到一个位置。你知道吗

相关问题 更多 >