Home > Software engineering >  Invert indices of two lists in Python
Invert indices of two lists in Python

Time:12-12

I need to compare two lists (list1 and list2) on sign changes and I want to invert those indices in the second list that undergo sign changes. This means that I want to change the -4 and the -11 in list2 to 4 and 11. How can I do this?

list1 = [1,4,5,6,8,10]
list2 = [3,10,-4,7,-11,10]

CodePudding user response:

Iterate over zip(list1, list2) and if a multiple of a pair is less than 0, change the sign of list2 item, else keep the sign unchanged:

out = [(j*(-1) if i*j < 0 else j) for i,j in zip(list1, list2)]

Output:

[3, 10, 4, 7, 11, 10]

CodePudding user response:

If I understand your question correctly, then you can do this fairly straightforward with list comprehension:

list3 = [j*-1 if i < 0 and j > 0 or i > 0 and j < 0 else j for i, j in zip(list1, list2)]

print(list3)

[3, 10, 4, 7, 11, 10]
  • Related