3

I haven't been able to figure this out. Thanks for any help:

Have:

>>> x = np.array([[1,2],[5,6]])
>>> x
array([[1, 2],
       [5, 6]])
>>> y = np.array([[3,4],[7,8]])
>>> y
array([[3, 4],
       [7, 8]])

Want:

>>> z = [[(1,2),(3,4)],[(5,6),(7,8)]]
>>> z
[[(1, 2), (3, 4)], [(5, 6), (7, 8)]]
llevar
  • 755
  • 8
  • 24
  • Possible duplicate of [Convert numpy array to tuple](https://stackoverflow.com/questions/10016352/convert-numpy-array-to-tuple) – gdlmx Mar 01 '19 at 01:16

6 Answers6

3

Try this:

x_z = map(tuple,x)
y_z = map(tuple,y)
[list(i) for i in zip(x_z, y_z)]

Output:

[[(1, 2), (3, 4)], [(5, 6), (7, 8)]]
Scott Boston
  • 147,308
  • 15
  • 139
  • 187
2

This is a fun problem. Here's what I came up with:

print([list(map(tuple, i)) for i in zip(x, y)])
# [[(1, 2), (3, 4)], [(5, 6), (7, 8)]]

Basically, zipping x and y gets you:

[(array([1, 2]), array([3, 4])), (array([5, 6]), array([7, 8])]

and so then you convert each element first into a list, and then a tuple

Paul H
  • 65,268
  • 20
  • 159
  • 136
0

If you want to run through the rows of each matrix, you can do this:

for (row1, row2) in zip(x,y):
    yield [tuple(row1), tuple(row2)]
       #  [ (1,2)     ,  (3,4)     ]

This will give you a generator (if you wrap it in a function), but you want a list. So instead, wrap it in a comprehension:

[ [tuple(row1),tuple(row2)] for (row1, row2) in zip(x,y) ]
Draconis
  • 3,209
  • 1
  • 19
  • 31
0
x = list([[1,2],[5,6]])
y = list([[3,4],[7,8]])
x
[[1, 2], [5, 6]]
y
[[3, 4], [7, 8]]
z=list(zip(x,y))
z
[([1, 2], [3, 4]), ([5, 6], [7, 8])]
Ray
  • 59
  • 5
  • Thanks, but this produces a list of tuples of lists, not a list of lists of tuples as requested. – llevar Mar 01 '19 at 07:56
0

IIUC

z=np.array([x,y])
[list(map(tuple,z[:,x]))for x in range(len(x))]
Out[223]: [[(1, 2), (3, 4)], [(5, 6), (7, 8)]]
BENY
  • 317,841
  • 20
  • 164
  • 234
-1

For what it's worth, here's the simplest and most efficient (but probably the least generalized) solution:

result = [[(x[0,0], x[0,1]), (y[0,0], y[0,1])],
         [(x[1,0], x[1,1]), (y[1,0], y[1,1])]]

Output:

[[(1, 2), (3, 4)], [(5, 6), (7, 8)]]

Admittedly, it doesn't generalize, but the question is -- in which direction is generalization required? Longer outer dimension? Longer inner dimension? The question hasn't called for any generalization.

Based on explicitly stated requirement, this solution can of course be modified to make it generalized just as much as needed.

fountainhead
  • 3,584
  • 1
  • 8
  • 17