合并2字节数组的最佳方法是什么?

时间:2017-08-26 18:51:36

标签: python

假设我有2个大数组(我在这个例子中放了较小的数组):

a1=bytes([10,20,30,40,50,60,70,80])
a2=bytes([11,21,31,41,51,61,71,81])

我想要做的是以这种方式合并这两个数组:

[10,20 , 11,21 , 30,40 , 31,41 , ...

我想要的是从第一个数组获取2个字节,然后从第二个数组获取2个等等。

这就是我所做的。它有效,但我认为有一种最好的方法可以做到这一点,而无需创建中间体数组:

a3 = bytearray()
for i in range(0, len(a1), 2):
    a3.append(a1[i])
    a3.append(a1[i+1])
    a3.append(b1[i])
    a3.append(b1[i+1])

output_array=bytes(a3)  # Very important: i need bytes() object at the end

4 个答案:

答案 0 :(得分:2)

您可以使用切片分配:

a1 = bytes([10,20,30,40,50,60,70,80])
a2 = bytes([11,21,31,41,51,61,71,81])

n = len(a1)

a3 = bytearray(2*n)
a3[0::4] = a1[0::2]
a3[1::4] = a1[1::2]
a3[2::4] = a2[0::2]
a3[3::4] = a2[1::2]
a3 = bytes(a3)

输出:

>>> a3
b'\n\x14\x0b\x15\x1e(\x1f)2<3=FPGQ'
>>> list(a3)
[10, 20, 11, 21, 30, 40, 31, 41, 50, 60, 51, 61, 70, 80, 71, 81]

编辑:这是一个没有中间副本的方法

def gen(a1, a2):
    i1 = iter(a1)
    i2 = iter(a2)
    while True:
        for it in i1, i1, i2, i2:
            try:
                yield next(it)
            except StopIteration:
                return

a3 = bytes(gen(a1, a2))

答案 1 :(得分:0)

从这里取出的块:How do you split a list into evenly sized chunks?
从这里合并:How do I merge two lists into a single list?

加入:

def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in range(0, len(l), n):
        yield l[i:i + n]

a1 = [10,20,30,40,50,60,70,80]
b1 = [11,21,31,41,51,61,71,81]
combined = [j for i in zip(chunks(a1, 2),chunks(b1, 2)) for j in i]
out = bytes(bytearray([x for pair in combined for x in pair]))
==> b'\n\x14\x0b\x15\x1e(\x1f)2<3=FPGQ'

答案 2 :(得分:0)

这是另一种选择:

a1=bytes([10,20,30,40,50,60,70,80])
a2=bytes([11,21,31,41,51,61,71,81])

merged = bytes((a1 if (i&3)<2 else a2)[i-(i&2)-2*(i>>2)]
               for i in range(2*len(a1)))

答案 3 :(得分:0)

直接在字节上使用切片分配

a1 = bytes([10,20,30,40,50,60,70,80])
a2 = bytes([11,21,31,41,51,61,71,81])
a3 = bytes()

for i in range(int(len(a1)/2)):
    a3 += a1[i*2:i*2+2] + a2[i*2:i*2+2]
# a3 = b'\n\x14\x0b\x15\x1e(\x1f)2<3=FPGQ'