import and package confusion

alex23 wuwei23 at gmail.com
Fri May 1 03:00:29 EDT 2009


On May 1, 4:24 pm, Arnaud Delobelle <arno... at googlemail.com> wrote:
> It's a challenge to do it in a list comprehension, but here it is!
> >>> data
> 'AAABBBBBCCCCCCCCCDD'
> >>> field_sizes
> [3, 5, 9, 2]
> >>> [data[i:j] for j in [0] for s in field_sizes for i, j in [(j, j+s)]]
> ['AAA', 'BBBBB', 'CCCCCCCCC', 'DD']

Ugh. I know using a listcomp was the point but I find using struct so
much more elegant.

>>> import struct
>>> data = 'AAABBBBBCCCCCCCCCDD'
>>> format = '3s5s9s2s'
>>> struct.unpack(format, data)
('AAA', 'BBBBB', 'CCCCCCCCC', 'DD')

Friends don't let friends abuse list comprehensions.

I made sure the code works this time :)



More information about the Python-list mailing list