简体   繁体   English

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

[英]How do I copy the contents of a bytearray to a list (Python)?

I have a dictionary which I convert to a bytearray, and since bytearrays are immutable (can't be modified) I try to make a list equal to each index in the bytearray. 我有一个字典,我转换为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))

The problem is it keeps printing IndexError: bytearray index out of range . 问题是它不断打印IndexError: bytearray index out of range
How and why is the bytearray out of range? bytearray如何以及为何超出范围?

If I correctly understood your question, you can simply use c = list(b) : 如果我正确理解了你的问题,你可以简单地使用c = list(b)

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

print(c)

Output: 输出:

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

In order to understand why you get this error, see this answer . 为了理解您收到此错误的原因,请参阅此答案

i is the value in b not the index ib不是索引

b = [1,5,20]
for i in b:
   print i #prints 1,then 5 , then 20

To fix your code: 要修复您的代码:

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

for i in b:
    c.append(i) 

or, better still, you can use the byte array directly with the list constructor and forgo the loop: 或者,更好的是,您可以直接使用字节数组与list构造函数并放弃循环:

c=list(b)

or, skip the byte array and use a list comprehension: 或者,跳过字节数组并使用列表解析:

c= [ord(ch) for ch in str(a)]

In all these cases, you get the list of ASCII ordinals if that is your goal: 在所有这些情况下,如果这是您的目标,您将获得ASCII序列列表:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM