spliting a list by nth items
Steven Bethard
steven.bethard at gmail.com
Thu Sep 23 14:36:55 EDT 2004
Larry Bates <lbates <at> swamisoft.com> writes:
>
> I believe you meant somthing like:
>
> non_nth_items = [items[i-1] for i in range(1,len(items)-1) if i % n]
Yeah, the items list is not of the form range(x) -- in fact, my current use
for this is with a list of filenames -- so Michael Hoffman's solution:
> > non_nth_items = [x for x in items if x % n]
wouldn't work. In the full fledged problem, I actually have a start parameter
for the slice as well as the step parameter (n), so I could probably do
something along these lines (inspired by your two suggestions):
non_nth_items = [item for i, item in enumerate(items) if (i - start) % n]
instead of my original
non_nth_items = list(items)
del non_nth_items[start::n]
The enumerate/range solution is a little more verbose, but it does only go
through the list once. Thanks for the good suggestions!
STeve
More information about the Python-list
mailing list