2

I have two lists: l1 and l2, which are shown below.

l1 = [0, 1, 1, 0, 1]
l2 = [0, 0, 1, 1, 0]

I want to sublist l1 into a list of lists based on values in l2, like below, one for '0' and one for '1'

[[0, 1, 1], [1, 0]]

this basically says, for 0 in l2, there are three values in l1 and for 1 in l2, there are two values in l1.

Is there a simple python way to do this?

EDIT: Here is what I have done to solve. This works well, but seems clunky and strange looking. I am looking for a more elegant solution.

d = [[],[]]
for i in range(len(l2)):
    d[l2[i]].append(l1[i])
2
  • What have you tried, and what precisely is the problem with it? This isn't a code writing service. Commented Mar 19, 2017 at 6:29
  • Edited my comment to include what I have done thus far Commented Mar 19, 2017 at 6:48

3 Answers 3

3
[[l1[n] for n, l2s in enumerate(l2) if l2s == element] for element in set(l2)]

Something like this might do the trick. set is just a bit faster.

Sign up to request clarification or add additional context in comments.

Comments

2

Basically your same algorithm, but a little more Pythonic. zip iterates the lists in parallel, giving you the first items, then the 2nd items, etc.:

l1 = [0, 1, 1, 0, 1]
l2 = [0, 0, 1, 1, 0]

L = [[],[]]
for a,b in zip(l1,l2):
    L[b].append(a)

Comments

0

I've assumed that you might have an arbitrary number of subsets defined by their "keys" in l2, and also that your keys are both sortable and hashable:

def partition(keys, values):
    unique_keys = sorted(set(keys))
    for key in unique_keys:
        yield [val for idx, val in enumerate(values) if keys[idx] == key]
    return

Using your two lists, l1 and l2, you could produce your list-of-lists like this:

list(partition(keys=l2, values=l1))

(Note that, technically, a partition is a function of sets, not lists, but I think it gets the idea across.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.