Skip to content Skip to sidebar Skip to footer

How To Split A List On A Condition?

By now I didn't find a convenient way to split a list by certain conditions, for example, I have a record list: a = ((0,1),(1,0),(0,2),(1,0),(3,0),(4,0),(0,3),(1,5)....) I want t

Solution 1:

Adding one line will make the loop more concise at the cost of readability (and FPness).

alist = []
blist = []
bothlists = [alist, blist]
for x in a:
  bothlists[x[0]].append(x)

Solution 2:

Well, the conditions are different, no wonder you need two loops. But if you want to sacrifice some readability,

aList, bList = [[x forxin a if x[0] == i] foriin (0, 1)]

Solution 3:

If you really want to make things complicated, you can import some functions from itertools to obfuscate your readable solution even more:

fromoperator import itemgetter
from collections import defaultdict

d = defaultdict(list)

forkey, value in itertools.groupby(a, itemgetter(0)):
    d[key].append(list(value))

Here is the output:

>>> print d[0]
[[(0, 1)], [(0, 2)], [(0, 3)]]
>>> print d[1]
[[(1, 0)], [(1, 0)], [(1, 5)]]
>>> print d[4]
[[(4, 0)]]

This code just groups the items into a dictionary using the value in the first tuple as the key. It's a little more generic than your code.

Solution 4:

I would use filter, see: http://docs.python.org/2/library/functions.html#filter

>>>a = ((0,1), (1,0), (0,2), (1,0), (3,0), (4,0), (0,3), (1,5))>>>filter(lambda x: x[0] == 1, a)
((1, 0), (1, 0), (1, 5))

To avoid redundant code you could collect the conditions in an iterable, like so:

>>>fs = (lambda x: x[0] == 0, lambda x: x[0] == 1)>>>for f in fs:...filter(f, a)...
((0, 1), (0, 2), (0, 3))
((1, 0), (1, 0), (1, 5))

Solution 5:

A dict can be more concise.

alist,blist= [], []
for x in a:
    {0:alist, 1:blist}.get(x[0]).append(x)

This is a flexible pattern that you can expand to cover other situations.

For example, you can add more choices. You can also gracefully deal with unexpected values by changing .get(x[0]) to .get(x[0], []).

Post a Comment for "How To Split A List On A Condition?"