Rachie Rachie - 1 year ago 79
Python Question

Merging 1D and 2D lists in python

I'm trying to set up data to convert to a numpy array. I have three lists. Two are one dimensional, and one is two dimensional.

a = [1,2,3]
b = [4,5,6]
c = [ [7,8],[9,10],[11,12] ]

I want to end up with this:

[ [1,4,7,8],[2,5,9,10],[3,6,11,12] ]

I've tried using
, but it doesn't delve into the 2D array.

Answer Source

Assuming you don't mind if the use of NumPy in the conversion itself, the following should work.

from numpy import array

a = array([1, 2, 3])
b = array([4, 5, 6])
c = array([[7, 8], [9, 10], [11, 12]])

result = array(list(zip(a, b, c[:, 0], c[:, 1])))

Note that c[:, n] will only work with NumPy arrays, not standard Python lists.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download