为倒计时跳过数字定义一个函数

00jrzges  于 2021-07-13  发布在  Java
关注(0)|答案(5)|浏览(308)
def count_down_skip(start, skip=0):
    """
    Counting down a sequence with a skip value,
    from a defined start point in reversed order.

    Args:
        start: start loop index.
        skip: number to skip over.

    Returns:
        (list): skipped list.

    """
    return [num for num in reversed(range(start + 1)) if num != skip]

print("... ".join(map(str, count_down_skip(10,1))) + "!")

这段代码可以输出10到0,没有1,而如果10到0没有1 4 3(跳过这些数字),那么我该怎么办?我试着改变指纹:

print("... ".join(map(str, count_down_skip(10,1,4,3))) + "!")

但是错误发生了。。。
在python中为倒计时数字定义一个函数

qq24tv8q

qq24tv8q1#

def count_down_skip(start, *args):
    return [num for num in reversed(range(start + 1)) if num not in args]

print("... ".join(map(str, count_down_skip(10,1,4,3))) + "!")

输入的参数不能多于函数定义中的参数。但是,您可以使用*args作为参数。这允许向函数输入可变数量的参数。

cbwuti44

cbwuti442#

您可以选择要跳过的数字列表。然后将每个列表项与 range(num+1) .

def count_down_skip(start, skip = []):
    return [num for num in reversed(range(start + 1)) if num not in skip]

print(count_down_skip(10,[1,4,3]))

# [10, 9, 8, 7, 6, 5, 2, 0]
vvppvyoh

vvppvyoh3#

你可以用 *args ,并检查 num 是成员:

def count_down_skip(start, *skips):
    return [num for num in reversed(range(start+1)) if num not in skips]

print(count_down_skip(10, 1, 4, 3))

输出:

[10, 9, 8, 7, 6, 5, 2, 0]
lx0bsm1f

lx0bsm1f4#

你的辩论太多了 count_down_skip 功能。如果要输入多个数字,可以使用列表,如下所示:

def count_down_skip(start, skip=0):
    """
    Counting down a sequence with a skip value,
    from a defined start point in reversed order.

    Args:
        start: start loop index.
        skip: number to skip over.

    Returns:
        (list): skipped list.

    """
    return [num for num in reversed(range(start + 1)) if num not in skip]

print("... ".join(map(str, count_down_skip(10, [1,4,3]))) + "!")
cx6n0qe3

cx6n0qe35#

最好的解决办法是,

def count_down_skip(start, *skip):
    return [num for num in reversed(range(start + 1)) if num not in skip]

print("... ".join(map(str, count_down_skip(10,1,4,3))) + "!")

相关问题