首页 > 解决方案 > 使用定义python简化多个if语句

问题描述

locationx, locationx, x,yairports是数组。

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]

如您所见,上面的代码两次执行相同的操作。有什么方法可以简化这一点,例如能够做出定义来检测 iflocationxlocationy == x[n]andy[n]吗?

标签: pythonpython-3.x

解决方案


我假设x, y,airplanes有两个以上的项目,因此最好将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这个

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

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

如果您有更多元素要检查,那么您可以使用range(len(airports))通常不喜欢的元素,因为您可以将其替换为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具有相同数量的元素,我可以用orlen(airports)代替len(x)len(y)


推荐阅读