gpt4 book ai didi

python - 如何将字节数组的内容复制到列表 (Python)?

转载 作者:行者123 更新时间:2023-11-28 19:56:54 24 4
gpt4 key购买 nike

我有一个字典,我将其转换为字节数组,并且由于字节数组是不可变的(无法修改),我尝试创建一个等于字节数组中每个索引的列表。

a = {1:'a', 2:'b', 3:'c'}
b = bytearray(str(a), 'ASCII')
c = []

for i in b:
c[i] = b[i] # Error on this line

print(str(c))

问题是它一直打印IndexError: bytearray index out of range
bytearray 如何以及为什么超出范围?

最佳答案

如果我正确理解了你的问题,你可以简单地使用 c = list(b):

a = {1:'a', 2:'b', 3:'c'}
b = bytearray(str(a), 'ASCII')
c = list(b)

print(c)

输出:

[123, 49, 58, 32, 39, 97, 39, 44, 
32, 50, 58, 32, 39, 98, 39, 44,
32, 51, 58, 32, 39, 99, 39, 125]

要了解为什么会出现此错误,请参阅 answer .

关于python - 如何将字节数组的内容复制到列表 (Python)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16843641/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com