Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matching occurrence of opposite number in a list python

Tags:

python

list

numpy

I have a list such has

results = [100, 100, -100, 100, -100, -100]

I would like to figure out the first occurrence of the opposite number. so first 100 would be match with the first -100, the second 100 would be match with the second -100.

I would like to have position as output such has:

[0, 2], [1, 4], [3, 5]

i.e : [0,2] represent the results[0] and results[2] where first occurrence of 100 is match with the first occurrence of -100

edit : you can assume there will always be the same amount of positive / negative and that the list will only contain 1 number

any help would be appricated

like image 757
Steven G Avatar asked Dec 06 '22 15:12

Steven G


1 Answers

For your simple case where the list only contains 2 integers (x and -x), you could simply zip() together the indexes:

indexes = [[],[]]
for i,x in enumerate(results):
    indexes[0].append(i) if x > 0 else indexes[1].append(i)
list(zip(*indexes))

Example:

>>> results = [100, 100, -100, 100, -100, -100]
>>> indexes = [[],[]]
>>> for i,x in enumerate(results): indexes[0].append(i) if x > 0 else indexes[1].append(i)
... 
>>> list(zip(*indexes))
[(0, 2), (1, 4), (3, 5)]

Note for small inputs 2 separate list comprehensions (e.g. [i for i,x in enumerate(results) if x > 0] may be faster than appending in a for loop.

like image 64
Chris_Rands Avatar answered Dec 22 '22 15:12

Chris_Rands