Reputation: 55
Can anyone help with creating lists with negative values out of a given list?
For example:
values = [1, 2, 3]
Desired output would be
[[-1, 2, 3], [1, -2, 3], [1, 2, -3],[-1, -2, 3], [1, -2, -3], [-1, 2, -3], [-1, -2, -3]]
Upvotes: 2
Views: 162
Reputation: 1121864
Produce the product of 3 times [1, -1]
and multiply the result with your input list:
from itertools import product
values = [1, 2, 3]
[[num * mul for num, mul in zip(values, combo)]
for combo in product([1, -1], repeat=len(values))]
Demo:
>>> from itertools import product
>>> values = [1, 2, 3]
>>> [[num * mul for num, mul in zip(values, combo)] for combo in product([1, -1], repeat=len(values))]
[[1, 2, 3], [1, 2, -3], [1, -2, 3], [1, -2, -3], [-1, 2, 3], [-1, 2, -3], [-1, -2, 3], [-1, -2, -3]]
The output order is slightly different from what you specified, but the same values are produced, plus the original list as the first element.
Upvotes: 2
Reputation: 2700
Another way to do it rather than having two list comprehensions is to like this
from itertools import *
print [[1*x[0], 2*x[1], 3*x[2]] for x in list(product([1,-1], repeat=3))]
[[1, 2, 3], [1, 2, -3], [1, -2, 3], [1, -2, -3], [-1, 2, 3], [-1, 2, -3], [-1, -2, 3], [-1, -2, -3]]
Since you know the values at the indexes of the list you can just multiply them by corresponding index in x. This however is not as flexible as using two list comprehensions like @Martijn's answer which can handle variable sized lists much easier.
Upvotes: 0