python 如何从 range() 函数中获取最后一个数字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/780057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:50:57  来源:igfitidea点击:

How do I get the last number from the range() function?

pythonrangefibonacci

提问by RedBlueThing

Is there a way to get the last number from the range()function? I need to get the last number in a Fibonacci sequence for first 20 terms or should I use a list instead of range()?

有没有办法从range()函数中获取最后一个数字?我需要获取前 20 项的斐波那契数列中的最后一个数字,还是应该使用列表而不是range()

回答by RedBlueThing

Not quite sure what you are after here but here goes:

不太确定你在这里追求什么,但这里有:

rangeList = range(0,21)
lastNumber = rangeList[len(rangeList)-1:][0]

or:

或者:

lastNumber = rangeList[-1]

回答by vezult

by in a range, do you mean last value provided by a generator? If so, you can do something like this:

by in a range,你的意思是生成器提供的最后一个值吗?如果是这样,您可以执行以下操作:

def fibonacci(iterations):
    # generate your fibonacci numbers here...


[x for x in fibonacci(20)][-1]

That would get you the last generated value.

这将为您提供最后生成的值。

回答by Stefan Kendall

I don't think anyone considered that you need fibonacci numbers. No, you'll have to store each number to build the fibonacci sequence recursively, but there is a formula to get the nth term of the fibonacci sequence.

我认为没有人认为您需要斐波那契数字。不,您必须存储每个数字以递归构建斐波那契数列,但有一个公式可以获取斐波那契数列的第 n 项。

Binet's Formula

比奈公式

If you need the last number of a list, use myList[-1].

如果需要列表的最后一个数字,请使用 myList[-1]。

回答by John T

Is this what you're after?

这是你追求的吗?

somerange = range(0,20)
print len(somerange) # if you want 20
print len(somerange)-1 # if you want 19

now if you want the number or item contained in a list...

现在,如果您想要列表中包含的数字或项目...

x = [1,2,3,4]
print x[len(x)-1]
# OR
print x[-1] # go back 1 element from current index 0, takes you to list end