Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Vertically merge two columns of a list of lists in Python

Input is shown below (my_list). This is actually list of hexadecimal numbers. Every pair of elements 0-1, 2-3, 4-5 form 16-bit signed integers, hence I need to merge every pair of elements.

my_list  = [['61', '00', '7B', '01', 'F2', '1F'],
       ['9A', 'FE', '8C', '02', '01', '22'],
       ['F4', 'FD', '60', '04', '35', '24']]

The output I would like to get is

aX =  ['6100', '9AFE', 'F4FD']
aY =  ['7B01', '8C02', '6004']
aZ =  ['F21F', '0122', '3524']

Right now I am doing it the following way. It works, but the issue is I have to keep adding more lines of code as the row length of my_list increases. Is there a better way?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

aX = [ x[0] + x[1]   for x in  my_list ]
aY = [ x[2] + x[3]   for x in  my_list ]
aZ = [ x[4] + x[5]   for x in  my_list ]

Appreciate your inputs!

>Solution :

You can combine map, zip like below:

>>> list(zip(*map(lambda x: [''.join(x[i:i+2]) for i in range(0, len(x), 2)], my_list)))
[('6100', '9AFE', 'F4FD'), ('7B01', '8C02', '6004'), ('F21F', '0122', '3524')]

Or as a nested list:

>>> list(map(list, zip(*map(lambda x: [''.join(x[i:i+2]) for i in range(0, len(x), 2)], my_list))))
[['6100', '9AFE', 'F4FD'], ['7B01', '8C02', '6004'], ['F21F', '0122', '3524']]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading