How to split a list on a condition?
python
Solution
Well, the conditions are different, no wonder you need two loops. But if you want to sacrifice some readability,
aList, bList = [[x for x in a if x[0] == i] for i in (0, 1)]
Problem
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 to split the content into 2 lists ``` alist = [] blist = [] for x in a: if x[0] == 0: alist.append(x) elif x[0] == 1: blist.append(x) ``` Not very concise. Written as list comprehensions: ``` aList = [x for x in a if x[0] == 0] bList = [x for x in a if x[0] == 1] ``` List comprehensions are usually good for reading and performance, but in this case the list must be iterated twice. Is there a better way to do this job?