我总共有 500 个浮点数,我想对每个浮点数运行 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 语句
你应该学习教程来学习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
您可以通过使用 tuples
list
并在其上循环来进一步缩短代码:
for value,name in [(x1, "x1"),(x2, "x2"),(x3, "x3"),(x4, "x4"),(0, "x0")]:
check_and_print(value,name) # outputs the same as above
多库:
- 功能
- 元组
- 列表
- 循环
- 字符串格式
如果数据不存储在一堆单独命名的变量中,如 x1
、x2
、... 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)
您没有指出数据的来源,但我怀疑它是由某种自动化过程生成的。如果您可以控制如何完成,那么更改内容应该不会太难,因此值采用建议列表的形式。