首页 > 解决方案 > 在 Python 中将数组作为参数传递

问题描述

我不确定这是否可能,但我正在尝试创建一个 python 程序来识别多项式并识别它们的所有属性。我试图制作一个类似于 switch() 函数的函数,以及我要为每种数量的参数情况制作数百个函数的方式,我想让其中一个参数成为一个数组,目前它是给我一堆错误,我真的不知道我应该做什么,因为他们没有解释自己,我环顾四周,没有找到任何有效的方法,任何帮助将不胜感激,我相当肯定在 python 中有一个类似的函数,但是任何关于它的文章都很令人困惑,谢谢,下面是我试图制作的函数。

def switch(checked, check):
    for(item in check):
        if(item == check):
            return True
    
    return False

标签: pythonarraysfunctionswitch-statementarguments

解决方案


如果您需要模拟 switch 语句,您可以使用这样的辅助函数:

def switch(v): yield lambda *c: v in c

然后,您可以以类似 C 的样式使用它:

x = 3
for case in switch(x):
    if case(1,2):
       # do something
       break
    if case(3):
       # do something else
       break
    if case(4,5,7):
       # do some other thing
       break
else:
    # handle other cases

或者您可以使用 if/elif/else 语句:

x = 3
for case in switch(x):
    if   case(1,2):   # do something
    elif case(3):     # do something else
    elif case(4,5,7): # do some other thing
    else:             # handle other cases

推荐阅读