简体   繁体   中英

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.

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 .
How and why is the bytearray out of range?

If I correctly understood your question, you can simply use 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

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:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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