python - 两个相关列表的列表理解,输出按第二个列表排序
问题描述
我正在尝试解决如何将这两个 for 循环转换为一个列表理解的问题。我们有这两个列表,我想根据第二个列表对第一个列表进行排序。使用 for 循环,它看起来像这样:
numbers = [-2, -8, 1, 17]
nov = [1, 2, 8, 17]
pon = []
for i in nov:
for x in numbers:
if abs(x) == i:
pon.append(x)
print(pon)
->>>[1, -2, -8, 17]
是否有可能将这两个循环写为列表理解?非常感谢您提前。
解决方案
您可以通过按照与嵌套逻辑相同的顺序对 for 循环和 if 条件进行排序,在列表推导中实现相同的输出。例如(重命名几个变量以使关系更加突出):
absolutes = [1, 2, 8, 17]
numbers = [-2, -8, 1, 17]
result = [n for a in absolutes for n in numbers if abs(n) == a]
print(result)
# [1, -2, -8, 17]
推荐阅读
- sql - SQL Server 2016:有连接和无连接的查询性能
- javascript - 如何按名称和列表过滤vue中的数组
- css - 如何为 SVG 添加阴影
? - php - 在 PHP 中将文件的编码更改为 UTF-8
- ios - iOS 中的状态栏会自行变暗
- php - 从上传的文件中读取内容时出现错误
- git - 在 kDiff3 中完成合并后如何触发自动命令?
- dart - 飞镖“向上转型”实际上并不是向上转型
- android - 如何在 Android 中使用 CameraX Jetpack 库进行直播?
- python - 在 Python 3 的 Pytz 模块中将 EST、CST 和 DST 时区转换为 unix 时间戳