How to rearrange the values in list based on the values in another list?

Viewed 75

I have a list as follows:

PastValues = [76978.359, 71079.933, 75580.227]

I did:

PastValues2 = PastValues + [-value for value in PastValues]

to create the negative values of the values in the PastValues and to join them with the values in the PastValues and it gave me the following list PastValues2:

[76978.359, 71079.933, 75580.227, -76978.359, -71079.933, -75580.227]

I would like to know if there is a way to rearrange the values in the PastValues2 to be of the same order as in PastValues.

Desired output:

PastValues2 = [-76978.359, 76978.359, -71079.933, 71079.933, -75580.227, 75580.227]

Since in the PastValues list 76978.359 was the first element, I want the first 2 elements in the PastValues2 to be the negative and the positive values of it, respectively. Similarly for the other elements in the PastValues list. The negative values should come before the positive values

5 Answers

you can use a list comprehension:

[e for i in PastValues for e in [-i, i]]

# [-76978.359, 76978.359, -71079.933, 71079.933, -75580.227, 75580.227]

You can iterate over the list and form negative and positive in each iteration. Finally flatten the obtained result to match with desired output:

from itertools import chain

PastValues = [76978.359, 71079.933, 75580.227]

result = list(chain.from_iterable(([-x, x] for x in PastValues)))
# [-76978.359, 76978.359, -71079.933, 71079.933, -75580.227, 75580.227]

Here's a NumPy based approach using broadcast multiplication:

(np.array(PastValues)*np.array([-1,1])[:,None]).ravel('F')

array([-76978.359,  76978.359, -71079.933,  71079.933, -75580.227,
        75580.227])

You can do it through double for cycle:

PastValues = [76978.359, 71079.933, 75580.227]

PastValues2 = [value*sign for value in PastValues for sign in [-1,1]]

# [-76978.359, 76978.359, -71079.933, 71079.933, -75580.227, 75580.227]

You can use operator.neg and itertools.chain. this will be more efficient than comprehensions, especially nested ones!

from itertools import chain
from operator import neg

PastValues = [76978.359, 71079.933, 75580.227]

PastValues2 = list(chain.from_iterable(zip(map(neg, PastValues), PastValues)))
Related