根据变量值调用不同的函数

2024-06-16 08:25:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我总共有500个float,我想对每个float运行if语句并相应地调用一个函数

我的代码是这样的:

x1 = .2
x2 = .33
x3 = -.422
x4 = -1

def function1():
    print("x1 is positive")

def function2():
    print("x2 is positive")

def function3():
    print("x3 is positive")

def function4():
    print("x4 is positive")

for x in range(10):    
    if x1 > 0:
        function1()

    if x2 > 0:
        function2()

    if x3 > 0:
        function3()

    if x4 > 0:
        function4()  

我想要一个更好更有效的方法,否则我必须为所有变量编写if语句


Tags: ifisdef语句floatprintx1x2
2条回答

您应该用tutorial(s)来学习python编码-这个问题是python的基本问题。你知道吗

创建一个检查变量并打印正确内容的函数:

x1 = .2
x2 = .33
x3 = -.422
x4 = -1

def check_and_print(value, variablename):
    """Checks if the content of value is smaller, bigger or euqal to zero. 
    Prints text to console using variablename."""
    if value > 0:
        print(f"{variablename} is positive")
    elif value < 0:
        print(f"{variablename} is negative")
    else:
        print(f"{variablename} is zero")

check_and_print(x1, "x1")
check_and_print(x2, "x2")
check_and_print(x3, "x3")
check_and_print(x4, "x4")
check_and_print(0, "carrot") # the given name is just printed

输出:

x1 is positive
x2 is positive
x3 is negative
x4 is negative
carrot is zero

通过使用listtuples和循环,可以进一步缩短代码:

for value,name in [(x1, "x1"),(x2, "x2"),(x3, "x3"),(x4, "x4"),(0, "x0")]:
    check_and_print(value,name)  # outputs the same as above

独行:

如果数据不是存储在一堆单独命名的变量中,比如x1x2。。。x500,正如您在评论中指出的。你知道吗

如果列表中的值如下所示:

values = [.2, .33, -.422, -1, .1, -.76, -.36, 1, -.6, .73, .22, .5,  # ... ,
         ]

然后它们都可以由一个在for循环中重复调用的函数来处理,如下所示:

def check_value(index, value):
    if value > 0:
        print('x{} is positive'.format(index+1))

for i, value in enumerate(values):
    check_value(i, value)

您还没有指出数据的来源,但我怀疑它是由某种自动过程生成的。如果您可以控制如何完成,那么更改内容应该不会太难,因此值以列表的形式显示。你知道吗

相关问题 更多 >