python - 使用定义python简化多个if语句
问题描述
locationx
, locationx
, x
,y
和airports
是数组。
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]
如您所见,上面的代码两次执行相同的操作。有什么方法可以简化这一点,例如能够做出定义来检测 iflocationx
和locationy
==
x[n]
andy[n]
吗?
解决方案
我假设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)
推荐阅读
- oracle - 以矢量化方式更新 oracle 中的列
- google-cloud-platform - 我们可以更改 GCP Cloud VPN 默认参数吗?
- angular - 用于 GraphQL 的 Angular ngrx 存储和 AWS Amplify API (Appsync)
- android - 如何在 Firebase 顶部安排最新帖子?
- javascript - Vue-router scrollBehavior:为什么 savedPosition 总是等于 { x: 0, y: 0 }?
- c# - 在 Xamarin 中将颜色转换为较深的阴影
- spring-boot - 春季云流-消费者配置不起作用
- angular - 提交Angular 6后将控件添加到最近的表单
- bash - /bin/bash 命令内函数的函数参数
- python - 强制 IPython 执行当前的多行代码块