简体   繁体   English

如何将列表和字典转换为字节?

[英]How do I convert lists and dictionaries into bytes?

I would like to convert lists and dictionaries into bytes.我想将列表和字典转换为字节。 I know that you can convert an string into bytes by doing:我知道您可以通过执行以下操作将字符串转换为字节:

"string".encode()

You can use bytearray for this.您可以为此使用字节数组。

nums = [1, 2, 3]
val = bytearray(nums)

print(val)

I think this will work fine.我认为这会很好。 For dictionary and list you can also use the following code.对于字典和列表,您还可以使用以下代码。 I prefer this:我更喜欢这个:

import json

d = {"a": "sldjkf", "b": "asod"}
s = json.dumps(d)
binary = ' '.join(format(ord(l), 'b') for l in s)

Use numpy's tobytes :使用 numpy 的tobytes

l = [0.1, 1.0, 2.0]
A = np.array(l)
A.tobytes()

Result:结果:

b'\x01\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00'

For dictionaries you can use the method mentioned ( json.dumps ) in the other answers to convert the dict into string and then into bytes.对于字典,您可以使用其他答案中提到的方法( json.dumps )将dict转换为字符串,然后转换为字节。

For list: you can use bytes() function from python.对于列表:您可以使用 python 中的 bytes() function。

For dictionaries: Convert dictionary to bytes and back again python?对于字典: 将字典转换为字节并再次返回 python?

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

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