简体   繁体   中英

Issue reversing a list in python 3

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

Okay so that's what I have so far. That gives the output [1, 1, 2, 3, 5, 8, 13, 21, 34]. Which is fine, but I need it reversed. Showing [34, 21, 13, 8, 5, 3, 2, 1, 1]. I just can't figure out how to apply the reversed command or use the [::-1] method.

I keep getting a bunch of errors if I try to apply any of the above methods. I'm pretty new at this. Thank you for your time.

Try this

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

There are some other ways around to reverse the list. All of them will work.

You can also use reverse method of list object

f35.reverse()
print(f35)

You can use any of this

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

OR

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

As an alternative, you could use insert instead of append to just build the list in the right order in the first place?

So instead of:

result.append(b)

Do:

result.insert(0, b)

That puts b at index 0 in the list and shoves all the other elements up one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM