Quantcast
Viewing all articles
Browse latest Browse all 41

Answer by Ymareth for How can I partition (split up, divide) a list based on a condition?

A generator based version, if you can put up with one or maybe two reversals of the original list.

A setup...

random.seed(1234)a = list(range(10))random.shuffle(a)a[2, 8, 3, 5, 6, 4, 9, 0, 1, 7]

And the split...

(list((a.pop(j) for j, y in [(len(a)-i-1, x) for i,x in enumerate(a[::-1])] if y%2 == 0))[::-1], a)([2, 8, 6, 4, 0], [3, 5, 9, 1, 7])
  1. Another list of tuples of locations and each element is built in reverse order.
  2. In a generator wrapped round that each element is tested against the predicate (here test for even) and if True then the element is poped using previously computed locations. We are working backwards along the list so poping elements out does not change positions closer to the beginning of the list.
  3. A wrapping list() evaluates the generator and a final revers [::-1] puts the elements back in the right order.
  4. The original list "a" now only contains elements that for which the predicate is False.

Viewing all articles
Browse latest Browse all 41

Trending Articles