使用python定义简化多个if语句

使用python定义简化多个if语句,python,python-3.x,Python,Python 3.x,locationx、locationx、x、y和Airport是阵列 if locationx[plane] == x[0] and locationy[plane] == y[0]: planelocation[plane] = airports[0] if locationx[plane] == x[1] and locationy[plane] == y[1]: planelocation[plane] = airports[1] 如您所见,上面的代码两次执行相同的操作。

locationx、locationx、x、y和Airport是阵列

if locationx[plane] == x[0] and locationy[plane] == y[0]:
    planelocation[plane] = airports[0]
if locationx[plane] == x[1] and locationy[plane] == y[1]:
    planelocation[plane] = airports[1]
如您所见,上面的代码两次执行相同的操作。是否有任何方法可以简化这一点,例如,能够定义位置x和位置y==x[n]和y[n]?

我假设x,y飞机有两个以上的项目,所以最好使用zip对它们进行分组,然后进行比较。坦率地说,您可以将这些信息放在一个列表或字典中

我还假设您搜索第一个匹配的数据,这样您就可以使用break跳过其他数据

我还将位置分配给较短的变量,因此代码较短,Python不必多次搜索列表中的同一元素

px = locationx[plane]
py = locationy[plane]

for temp_x, temp_y, temp_airports in zip(x, y, airports): 
    if px == temp_x and py == temp_y:
         planelocation[plane] = temp_airports
         break # don't check others
我找不到更好的变量名称,所以我使用了前缀temp_

正如你所建议的,你可以用n来做这个

如果您有更多的元素要检查,那么您可以使用rangelenairports,这通常不是首选的,因为您可以用zip或其他更可读的方法替换它

for n in range(len(airports)):
    if px == x[n] and py == y[n]:
         planelocation[plane] = airports[n]
         break # don't check others

我假设x,y,airplanes有相同数量的元素,我可以使用lenx来代替lenx或leny

只需使用and。共享变量locationx,locationy中的内容,机场和planelocation会让你知道你要做什么。在for循环中放置两个条件之一,并用循环变量替换索引号。还要确保语法正确:如果->和。可以将locationx[plane],locationy[plane]分配给名称较短的变量,以缩短代码。Python不需要在列表中搜索两次;印刷位置;printx;普林蒂
for n in range(len(airports)):
    if px == x[n] and py == y[n]:
         planelocation[plane] = airports[n]
         break # don't check others