-1

I have a list of (x, y) coordinates and would like to expand the list as follows:

Input:

l = [[1, 2], [5, 2]]

Output:

l = [[1, 2], [2, 1], [-1, 2], [2, -1], [1, -2], [-2, 1], [-1, -2], [-2, -1], [5, 2],...]

I can only think of complicated ways to do this. Are there simple ways to do this? Which functions should I consider using?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
eigenvector
  • 313
  • 1
  • 3
  • 12

3 Answers3

1

You can use zip and map

l =  [[1,2], [5,2]]

[list(map(lambda x: ((-1)**int(x[-1])*x[0]), zip(j, bin(k)[2:].zfill(len(l[0]))))) for i in l for j in [i, i[::-1]] for k in range(2**len(l[0]))]
[[1, 2],
 [1, -2],
 [-1, 2],
 [-1, -2],
 [2, 1],
 [2, -1],
 [-2, 1],
 [-2, -1],
 [5, 2],
 [5, -2],
 [-5, 2],
 [-5, -2],
 [2, 5],
 [2, -5],
 [-2, 5],
 [-2, -5]]
Epsi95
  • 8,832
  • 1
  • 16
  • 34
  • This is actually pretty simple. Taking `list` and `reversed list` and then making the 4 combination for each – Epsi95 Feb 08 '21 at 14:41
  • Just to mention it will work for 2 element sublist only. But more than 2 can be achieved using `itertools` `permutation` in place `[i, i[::-1]] ` – Epsi95 Feb 08 '21 at 14:42
1

Inspired from this answer, I found this :

l =  [[1,2], [5,2]]
res = []

for indexes in l:
    l1 = [indexes[0], -indexes[0]]
    l2 = [indexes[1], -indexes[1]]
    res += [elem for x in itertools.permutations(l1,2) for elem in itertools.chain(zip(x,l2),zip(l2,x))]

And you can one-line it as such :

l =  [[1,2], [5,2]]
[elem for idx in l for x in itertools.permutations([idx[0], -idx[0]],2) for elem in itertools.chain(zip(x,[idx[1], -idx[1]]),zip([idx[1], -idx[1]],x))]
Naeio
  • 1,112
  • 7
  • 21
1

One way to look at this is that you want all combinations of the first number positive/negative with the second number positive/negative, and then the same with reverse order.

So you can create the product of each ordering as described above:

import itertools

l = [1, 2]
num1 = [abs(l[0]), -abs(l[0])]
num2 = [abs(l[1]), -abs(l[1])]
print(list(itertools.product(num1, num2)))
print(list(itertools.product(num2, num1)))

Which will give:

[(1, 2), (1, -2), (-1, 2), (-1, -2)]
[(2, 1), (2, -1), (-2, 1), (-2, -1)]
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61