[英]How do I create a function that returns a list of integers from n to 1?
How do I write a function called countdown
that counts down starting from n
and goes until 1 ? 如何编写一个称为
countdown
的函数,该函数从n
开始countdown
直到1? The function should return a list
, the contents of which should be integers going from n
down to 1. 该函数应返回一个
list
,其内容应为从n
到1的整数。
def countdown(n):
if n >= 1:
countdown(n-1)
print(n)
Since you want to return a list
, you need to create that list in the function. 由于要返回
list
,因此需要在函数中创建该列表。
def countdown(n):
return list(range(n, 0, -1))
range
creates your sequence from n to 0 (non-inclusive, which means it'll stop at 1), with a step of -1 each time. range
会创建从n到0(不包含在内,这意味着它将在1处停止)的序列,每次的步长为-1。
list
then converts the sequence into the list that you want returned. list
然后将序列转换为要返回的列表。
This also means that you don't actually have to create a specific function for a countdown list. 这也意味着您实际上不必为倒数列表创建特定的功能。 You can just directly call
list(range(n, 0, -1))
. 您可以直接调用
list(range(n, 0, -1))
。
Using recursion: 使用递归:
def countdown(n):
if n < 1:
return []
return [n] + countdown(n-1)
This approach provides the "base case" and creation of a list of integers once the base is reached. 一旦达到基数,此方法将提供“基本情况”并创建整数列表。
Check out this link to visualize the execution. 签出此链接以可视化执行。 Do let me know if you have any questions.
如果您有任何疑问,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.