top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Split a list into two parts based on a filter in python

0 votes
610 views

I have a list, songs, which I want to divide into two groups.
Essentially, I want:

new_songs = [s for s in songs if s.is_new()]
old_songs = [s for s in songs if not s.is_new()]

but I don't want to make two passes over the list. I could do:

new_songs = []
old_songs = []
for s in songs:
 if s.is_new():
 new_songs.append(s)
 else:
 old_songs.append(s)

Which works, but is klunky compared to the two-liner above. This seems like a common enough thing that I was expecting to find something in itertools which did this. I'm thinking something along the lines of:

matches, non_matches = isplit(lambda s: s.is_new, songs)

Does such a thing exist?

posted Jun 10, 2013 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote

You could do something like:

new_songs, old_songs = [], []
[(new_songs if s.is_new() else old_songs).append(s) for s in songs]

But I'm not sure that that's any better than the long version.

answer Jun 10, 2013 by anonymous
+1 vote

itertools.groupby() is kinda similar, but unfortunately doesn't fit the bill due to its sorting requirement.
There is regrettably no itertools.partition(). And given how dead-set Raymond seems to be against adding things to the itertools module, there will likely never be.
Maybe more-itertools ( https://pypi.python.org/pypi/more-itertools )
would accept a patch?

answer Jun 10, 2013 by anonymous
Similar Questions
0 votes

Hi,

I have a list of arbitrary length, and I need to split it up into equal size chunks. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.

I was wondering if anyone had a good solution to this for lists of any length

This should work:

l = range(1, 1000)
print chunks(l, 10) -> [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ]

I was looking for something useful in itertools but I couldn't find anything obviously useful.

Appretiate your help.

+1 vote

How can I use the '.split()' method (am I right in calling it a method?) without instead of writing each comma between words in the pie list in the following code? Also, is there a way to use .split instead of typing the apostrophes?

import random
pie=['keylime', 'peach', 'apple', 'cherry', 'pecan']
print(random.choice(pie))
+3 votes

Input:
[1 7 15 29 11 9]

Output:
[9 15] [1 7 11 29]

Average of first part: (15+9)/2 = 12,
Average of second part: (1 + 7 + 11 + 29) / 4 = 12

0 votes

I'm new to Django. Is there any tell how to add a limit filter in Django?

...