如何在python中返回偶数参数列表?

问题描述 投票:0回答:2

定义一个名为myfunc()的函数,该函数采用任意值,如果参数为偶数,则返回参数列表。下面是我写的代码

def myfunc(*args):
    if args%2==0:
        return list(args)
    else:
        pass

错误是:

unsupported operand type(s) for %: 'tuple' and 'int'

但是我在我的代码中找不到错误。

请帮助!

python-3.x
2个回答
0
投票

*args是参数的元组。您不能直接对它使用模。同样,如果您要退货,则在任何情况下都应始终退货。

如果传递偶数个参数,它将返回列表中的参数:

def myfunc(*args):
    if len(args) % 2 == 0:
        return list(args)
    return None

这将仅返回偶数的参数:

def myfunc(*args):
    return [x for x in args if x % 2 == 0]

0
投票

如果您需要所有arg都是偶数,则可以尝试:

def myfunc(*args):
    # Check all args are ints. Could allow other types if needed
    if not all([isinstance(a, int) for a in args]):
        return
    if all([a%2 == 0 for a in args]):
        return list(args)
    return 

这给出以下内容:

myfunc(2,4,'a',8)
> None
myfunc(2,4,6,8)
> [2,4,6,8]
myfunc(2,4,5,8)
> None
© www.soinside.com 2019 - 2024. All rights reserved.