In R, you could split a vector according to the factors of another vector:
> a <- 1:10
[1] 1 2 3 4 5 6 7 8 9 10
> b <- rep(1:2,5)
[1] 1 2 1 2 1 2 1 2 1 2
> split(a,b)
$`1`
[1] 1 3 5 7 9
$`2`
[1] 2 4 6 8 10
Thus, grouping a list (in terms of python) according to the values of another list (according to the order of the factors).
Is there anything handy in python like that, except from the itertools.groupby
approach?
From your example, it looks like each element in b contains the 1-indexed list in which the node will be stored. Python lacks the automatic numeric variables that R seems to have, so we'll return a tuple of lists. If you can do zero-indexed lists, and you only need two lists (i.e., for your R use case, 1 and 2 are the only values, in python they'll be 0 and 1)
Then you can use
itertools.compress
:If you need more general input (multiple numbers), something like the following will return an n-tuple:
Edit: warning, this a
groupby
solution, which is not what OP asked for, but it may be of use to someone looking for a less specific way to split the R way in Python.Here's one way with
itertools
.This gives you a dictionary, which is analogous to the named list that you get from R's
split
.As a long time R user I was wondering how to do the same thing. It's a very handy function for tabulating vectors. This is what I came up with:
You could try:
results in:
To make this generalise you can simply iterate over the unique elements in b: