Split a list into two parts based on a filter?

Serhiy Storchaka storchaka at gmail.com
Wed Jun 12 12:28:45 EDT 2013


12.06.13 09:32, Phil Connell написав(ла):
> On 12 Jun 2013 01:36, "Roy Smith" <roy at panix.com <mailto:roy at panix.com>>
> wrote:
>  > Well, continuing down this somewhat bizarre path:
>  >
>  > new_songs, old_songs = [], []
>  > itertools.takewhile(
>  >     lambda x: True,
>  >     (new_songs if s.is_new() else old_songs).append(s) for s in songs)
>  >     )
>  >
>  > I'm not sure I got the syntax exactly right, but the idea is anything
>  > that will iterate over a generator expression.  That at least gets rid
>  > of the memory requirement to hold the throw-away list :-)
>
> You could equivalently pass the generator to deque() with maxlen=0 -
> this consumes the iterator with constant memory usage.

any((new_songs if s.is_new() else old_songs).append(s) for s in songs)





More information about the Python-list mailing list