spliting a list by nth items

Elaine Jackson elainejackson7355 at home.com
Fri Sep 24 10:06:43 CEST 2004


>>> x = [0,1,2,3,4,5,6,7,8,9]
>>> n = 3
>>> y = [x[i] for i in range(len(x)) if i%n==0]
>>> z = [x[i] for i in range(len(x)) if i%n<>0]
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> y
[0, 3, 6, 9]
>>> z
[1, 2, 4, 5, 7, 8]


"Steven Bethard" <steven.bethard at gmail.com> wrote in message
news:mailman.3802.1095960335.5135.python-list at python.org...
| I feel like this has probably been answered before, but I couldn't
| find something quite like it in the archives.  Feel free to point me
| somewhere if you know where this has already been answered.
|
| I have a list in a particular order that I want to split into two
| lists: the list of every nth item, and the list of remaining items.
| It's important to maintain the original order in both lists.
|
| So the first list is simple:
|
| nth_items = items[::n]
|
| The second list is what's giving me trouble.  So far, the best I've
| come up with is:
|
| non_nth_items = list(items)
| del non_nth_items[::n]
|
| Is this the right way to do this?
|
| Steve
| --
| You can wordify anything if you just verb it.
|         - Bucky Katt, Get Fuzzy





More information about the Python-list mailing list