Is there an easier way to express this list slicing?
horpner at yahoo.com
Thu Nov 30 20:23:17 CET 2006
On 2006-11-30, John Henry <john106henry at hotmail.com> wrote:
> If I have a list of say, 10 elements and I need to slice it into
> irregular size list, I would have to create a bunch of temporary
> variables and then regroup them afterwords, like:
> # Just for illustration. Alist can be any existing 10 element list
> That obviously work but do I *really* have to do that?
Please post actual code we can run, rather than text that is
almost, but not quite, entirely unlike Python code.
> BTW: I know you can do:
Note that alist and blist are not necessarily lists, as you did
not use slice notation.
> but I don't see that it's any better.
I think it looks much better, personally.
If you are iterating through that sequence of slices a lot,
consider using a generator that yields the sequence.
>>> def parts(items):
... yield items[0:1]
... yield items[1:2]
... yield items[2:5]
... yield items[5:]
>>> for seq in parts(range(10)):
... print seq
[2, 3, 4]
[5, 6, 7, 8, 9]
I guess there are some operas I can tolerate and Italian isn't one of them.
--Music Lit Essay
More information about the Python-list