[英]Vertically merge two columns of a list of lists in Python
Input is shown below (my_list).输入如下所示(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.每对元素 0-1、2-3、4-5 形成 16 位有符号整数,因此我需要合并每一对元素。
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.它有效,但问题是随着 my_list 行长度的增加,我必须不断添加更多代码行。 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!感谢您的投入!
You can combine map
, zip
like below:您可以组合map
, zip
如下所示:
>>> 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']]
You can use a list comprehension with str.join
to concatenate every two items, and zip
to transpose:您可以使用带有str.join
的列表推导来连接每两个项目,并使用zip
进行转置:
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'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.