在 Python 中将整数列表转换为字节数组

e04*_*e04 2 python bytearray list python-2.7 python-3.x

我是 Python 的新手(C 是我的主要语言),所以这可能是一个超级基本/幼稚的问题。

我有两个使用以下 Python 代码生成的整数列表:

mainList = range(100)
random.shuffle(mainList)
list1 = mainList[:len(mainList)/2]
list2 = mainList[len(mainList)/2:]
Run Code Online (Sandbox Code Playgroud)

基本上,我试图通过 TCP 连接发送这些列表(list1list2)中的每一个,并且我想确保我只为每个列表发送 50 字节的有效负载(每个列表包含 50 个整数)。

什么是最好的方法来做到这一点?该bytearray()功能是否适用于这里?

Mar*_*ans 5

您可以使用以下方法。首先使用 Python 的struct模块将整数列表打包成二进制,每个整数使用 4 个字节。在I指定的尺寸要求,因此,如果你的整数是唯一的字节值,你可以这样改变B

zipiter然后被用于在从字节列表的时间以抢50个字节。这意味着您可以将其设置为您喜欢的任何长度:

import random
import struct

main_list = range(100)
random.shuffle(main_list)

# 'I' meaning unsigned int of 4 bytes
bytes = struct.pack("{}I".format(len(main_list)), *main_list)

for send_50 in zip(*[iter(bytes)]*50):
    print len(send_50)
Run Code Online (Sandbox Code Playgroud)

使用 Python 2.7 测试