python - 如何在循环中只运行我的部分代码?

标签 python

我正试图找到一种方法来优化我的代码。目前我有一个 while 循环,其中读取了几个传感器。但是在我的代码开始时,我首先检查需要读取哪些传感器,然后我只是在代码的每一部分之前添加一个 if 函数。有更好的方法吗?

sensor1_actif=1
sensor2_actif=0

while True:
    if(sensor1_actif==1):
        x=sensor1read()
    
    if(sensor2_actif==1):
        y=sensor2read()

    ...

最佳答案

您可以使用 for 循环:

funcs = [sensor1read, sensor2read, ...] # Store the functions in order
while True:
    actifs = [sensor1_actif, sensor2_actif, ...] # Store the variables in order
    sensor_readings = [None for _ in range(len(funcs))]
    for i, (func, actif) in enumerate(zip(funcs, actifs)): # Iterate through
        if actif: # Equivalent to if actif != 0
            sensor_readings[i] = func()

这会将输出存储在列表中。 sensor_readings[0] 将是第一个函数的输出,sensor_readings[1] 是第二个函数的输出,等等。如果函数没有被调用,则默认为

关于python - 如何在循环中只运行我的部分代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73324606/

相关文章:

python - 使用 LocMemCache 进行选择性 Django pytest

python - 构建共享 python 库表单 .cpp 文件时缺少 opencv 库

Python - 从文件中提取 excel 文档,需要帮助读取数据

python - 使用 python 从 Azure 机器学习服务连接 Azure SQL 数据库时出错

带网格的 Python SAC 图

Python递归生成器性能

python - 在 python 中使用数据框实现函数

Python Social Auth Django 模板示例

python - 仅当我使用 PsExec 将其作为远程服务运行时编译失败

python - 2.7 中与 future 兼容的枚举?