我想将列表和字典转换为字节。 我知道您可以通过以下方式将字符串转换为字节:
"string".encode()
答案 0 :(得分:1)
您可以为此使用字节数组。
nums = [1, 2, 3]
val = bytearray(nums)
print(val)
我认为这会很好。对于字典和列表,您还可以使用以下代码。我喜欢这个:
import json
d = {"a": "sldjkf", "b": "asod"}
s = json.dumps(d)
binary = ' '.join(format(ord(l), 'b') for l in s)
答案 1 :(得分:1)
使用numpy的tobytes
:
l = [0.1, 1.0, 2.0]
A = np.array(l)
A.tobytes()
结果:
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'
对于字典,您可以使用其他答案中提到的方法(json.dumps
将dict
转换为字符串,然后转换为字节。
答案 2 :(得分:0)
对于列表: 您可以使用python中的bytes()函数。