Home > Enterprise >  Vertically merge two columns of a list of lists in Python
Vertically merge two columns of a list of lists in Python

Time:06-27

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?

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!

CodePudding user response:

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']]

CodePudding user response:

You can use a list comprehension with str.join to concatenate every two items, and zip to transpose:

aX, aY, aZ = map(list, zip(*([''.join(l[i:i 2]) for i in range(0, len(l), 2)]
                             for l in my_list)))

output:

aX
# ['6100', '9AFE', 'F4FD']

aY
# ['7B01', '8C02', '6004']

aZ
# ['F21F', '0122', '3524'])
  • Related