# Partition list satisfying conditions

Hi, I am looking for a function which will partition a list. For a simple example, suppose I have the list [1,2,3,4,5,6]. Suppose I want all the even integers in one list and the odd integers in another. Is there a function that can do this, and perhaps yeild something like [[1,3,5],[2,4,6]]? In this case, the number of partitions is 2, so it is fairly easy, but in my problem the number is not known. In mathematica, the function I want is called GatherBy.

edit retag close merge delete

Sort by » oldest newest most voted For the particular example you have you can try

sage: l=range(10)
sage: odd=filter(lambda x: x%2, l)
sage: even=filter(lambda x: x%2==0, l)
sage: odd
[1, 3, 5, 7, 9]
sage: even
[0, 2, 4, 6, 8]


Otherwise you can try implementing a naive version of gather_by using dictionaries as follows

def gather_by( l, f ):
parts = {}
for e in l:
cur_key = f(e)
if parts.has_key( cur_key ):
parts[cur_key].append( e )
else:
parts[cur_key] = [ e ]
return parts.values()


Then

sage: gather_by( range(10), lambda x: x%2)
[[0, 2, 4, 6, 8], [1, 3, 5, 7, 9]]

more