如何将bytearray的内容复制到列表(Python)?

Jos*_*ber 2 python dictionary bytearray python-3.x

我有一个字典,我转换为bytearray,因为bytearrays是不可变的(无法修改)我尝试使列表等于bytearray中的每个索引.

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))
Run Code Online (Sandbox Code Playgroud)

问题是它继续打印IndexError: bytearray index out of range.
bytearray如何以及为何超出范围?

Sam*_*uns 5

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

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

print(c)
Run Code Online (Sandbox Code Playgroud)

输出:

[123, 49, 58, 32, 39, 97, 39, 44, 
 32, 50, 58, 32, 39, 98, 39, 44, 
 32, 51, 58, 32, 39, 99, 39, 125]
Run Code Online (Sandbox Code Playgroud)

为了理解您收到此错误的原因,请参阅此答案.