Packing a list of lists with struct.pack()
Fredrik Lundh
fredrik at pythonware.com
Mon Apr 24 12:56:43 EDT 2006
Panos Laganakos wrote:
> I have a list that includes lists of integers, in the form of:
> li = [[0, 1, 2], [3, 4, 5], ...]
> What can I do to get li as a single list of integers?
>
> I tried list comprehension in the form of:
> [([j for j in i]) for i in li]
>
> But that doesn't seem to work, any ideas?
you have it backwards: a nested list expression is like a nested
for loop, but with the innermost expression at the beginning. a
for-loop would look like:
for i in li:
for j in i:
... do something with j ...
so the corresponding comprehension is
[j for i in li for j in i]
which gives you the expected result. when you pass this to pack,
you can use a generator expression instead:
data = struct.pack("%di" % (len(li)*3), *(j for i in li for j in i))
</F>
More information about the Python-list
mailing list