Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging 1D and 2D lists in python

Tags:

python

list

numpy

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 zip(), but it doesn't delve into the 2D array.

like image 321
Rachie Avatar asked Jun 03 '16 01:06

Rachie


1 Answers

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.

like image 115
2Cubed Avatar answered Sep 30 '22 09:09

2Cubed