-1

I am trying to solve the problem how to transfer these two for loops into one list comprehension. We have these two lists and I would like to sort the first list according to the second list. With for loops it looks like this:

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]

Is it somehow possible write these two loops as list comprehension? Thank you very much in advance.

benvc
  • 14,448
  • 4
  • 33
  • 54
J. Krc
  • 47
  • 3

1 Answers1

0

You can achieve the same output in a list comprehension by sequencing your for loops and your if condition in the same order as your nested logic. For example (renamed a couple variables to make the relationships stand out a bit more):

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]
benvc
  • 14,448
  • 4
  • 33
  • 54