简体   繁体   English

如何创建一个返回从n到1的整数列表的函数?

[英]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.

相关问题 如何制作一个 function,它返回列表 n 中参数 n1 或 n2 的倍数的所有整数 - How to make a function that returns all integers that are multiples of either parameters n1 or n2 within the list n 如何从一个整数列表和一个布尔值列表创建一个列表? (Python) - How do I create a list from one list of integers and one list of booleans? (Python) 如何从字符串列表中提取整数以创建公式? - How can I extract integers from a list of strings to create a formula? 如何从 python 中的整数列表中 append 项目列表 n 次? - How can I append a list of items n times from a list of integers in python? 如何将元组和整数列表转换为嵌套字典? - How do I convert from a list of tuples and integers to a nested dictionary? 如何从整数列表中选择几个最大值? - How do I choose several maximum values from a list of integers? 如何将整数列表拆分为数字整数列表? - How do I split a list of integers into a list of digit integers? 如何从我拥有的这个 function 创建一个 n-gram function? - How to create a n-gram function from this function that I have? Function 生成“n”个不可重复的非负随机整数并将它们返回到列表中 - Function that generates "n" non-repeatable nonnegative random integers and returns them in a list 如何从DataFrame创建整数列表? - How to create a list of lists of integers from DataFrame?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM