2

I'm brand new to Python (C is my main language), so this may be a super basic/naive question.

I have two lists of integers that I'm generating with the following Python code:

mainList = range(100)
random.shuffle(mainList)
list1 = mainList[:len(mainList)/2]
list2 = mainList[len(mainList)/2:]

Basically, I'm trying to send each of these lists (list1 and list2) over a TCP connection, and I want to make sure that I'm only sending a 50-byte payload for each (each list contains 50 integers).

What would be the best way to do this? Would the bytearray() function be applicable here, at all?

the
  • 21,007
  • 11
  • 68
  • 101
e04
  • 75
  • 1
  • 2
  • 7

1 Answers1

5

You could use the following method. First use Python's struct module to pack your list of integers into binary, using 4 bytes per integer. The I specifies the size required, so if your integers are only byte values, you could change this to B.

zip and iter are then used to grab 50 bytes at a time from the byte list. This would then mean you could make it any length you like:

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)

Tested using Python 2.7

Martin Evans
  • 45,791
  • 17
  • 81
  • 97
  • Is this a common idiom? It took me a couple of minutes to figure out how it works, and I think I'd have been flummoxed if I came across it in code. – saulspatz Sep 10 '15 at 12:17
  • Fairly common, it is based on the `grouper` [recipe](https://docs.python.org/2/library/itertools.html#recipes). – Martin Evans Sep 10 '15 at 12:20
  • Thanks! I didn't even know about those itertools recipes; you can learn something new about python very day. – saulspatz Sep 10 '15 at 12:36
  • Thanks, Martin! Your answer definitely gave me a nice primer to struct.pack() and zip() + iter(), before looking them up in the Py documentation. Also, your method is much more concise than I would've thought up! Can't wait to learn more as I go along with the language. Thanks again. – e04 Sep 12 '15 at 03:52