首页 > 解决方案 > 两个相关列表的列表理解,输出按第二个列表排序

问题描述

我正在尝试解决如何将这两个 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]

是否有可能将这两个循环写为列表理解?非常感谢您提前。

标签: pythonlist-comprehension

解决方案


您可以通过按照与嵌套逻辑相同的顺序对 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]

推荐阅读