将bytearray插入到bytearray Python中 [英] Insert bytearray into bytearray Python

查看:220
本文介绍了将bytearray插入到bytearray Python中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在开始时将一个字节数组插入另一个字节数组.这是我要完成的工作的简单示例.

I'm trying to insert one byte array into another at the beginning. Here's a simple example of what I'm trying to accomplish.

import struct
a = bytearray(struct.pack(">i", 1))
b = bytearray(struct.pack(">i", 2))
a = a.insert(0, b)
print(a)

但是,此操作失败并显示以下错误:

However this fails with the following error:

a = a.insert(0, b) TypeError: an integer is required

推荐答案

bytearray是序列类型,它支持基于切片的操作.带有切片的在位置i插入"惯用法像这样的x[i:i] = <a compatible sequence>.因此,对于拳头位置:

bytearray is a sequence-type, and it supports slice-based operations. The "insert at position i" idiom with slices goes like this x[i:i] = <a compatible sequence>. So, for the fist position:

>>> a
bytearray(b'\x00\x00\x00\x01')
>>> b
bytearray(b'\x00\x00\x00\x02')
>>> a[0:0] = b
>>> a
bytearray(b'\x00\x00\x00\x02\x00\x00\x00\x01')

对于第三位置:

>>> a
bytearray(b'\x00\x00\x00\x01')
>>> b
bytearray(b'\x00\x00\x00\x02')
>>> a[2:2] = b
>>> a
bytearray(b'\x00\x00\x00\x00\x00\x02\x00\x01')

注意,这不等同于.insert,因为对于序列,.insert 将整个对象插入为ith元素.因此,请考虑以下带有列表的简单示例:

Note, this isn't equivalent to .insert, because for sequences, .insert inserts the entire object as the ith element. So, consider the following simple example with lists:

>>> y = ['a','b']
>>> x.insert(0, y)
>>>
>>> x
[['a', 'b'], 1, 2, 3]

真正想要的是:

>>> x
[1, 2, 3]
>>> y
['a', 'b']
>>> x[0:0] = y
>>> x
['a', 'b', 1, 2, 3]

这篇关于将bytearray插入到bytearray Python中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆