方括号中的函数参数

时间:2014-05-07 10:31:18

标签: python python-3.x

当我在Python shell中调用我的函数时,我希望布尔参数列表在常规括号和方括号内,如so_animal([True,True,True,True,True,True,True])如果有人也可以解释它所使用的过程非常有用。

这是我的任何参考代码

which_animal(backbone,shell,six_legs,give_birth_to_live_babies,feathers,gills,lay_eggs_in_water):

if backbone:
    if give_birth_to_live_babies:
        return 'Mammal'
    if feathers:
        return 'Bird'
    if gills:
        return 'Fish'
    if lay_eggs_in_water:
        return 'Amphibian'
    if not lay_eggs_in_water:
        return 'Reptile'

if not backbone:
    if shell:
        return 'Mollusc'
    if six_legs:
        return 'Insect'
    if not six_legs:
        return 'Arachnid'

1 个答案:

答案 0 :(得分:1)

您可以使用boolean解压缩*列表来传递它。您将如何做到这一点:

which_animal(*[True,True,True,True,True,True,True])

这样,您就不需要对方法进行任何调整。

DEMO

或者,您可以让which_animal方法接受列表,但此代码本身很难理解。

def which_animal(l):
    if l[0]:
        if l[3]:
            return 'Mammal'
        if l[4]:
            return 'Bird'
        if l[5]:
            return 'Fish'
        if l[6]:
            return 'Amphibian'
        if not l[6]:
            return 'Reptile'

    if not l[0]:
        if l[1]:
            return 'Mollusc'
        if l[2]:
            return 'Insect'
        if not l[2]:
            return 'Arachnid'

>>> print which_animal([True,True,True,True,True,True,True])
Mammal
相关问题