M.Cong
M.Cong

Reputation: 79

Slice list based on values in another list

I have long lists, for example:

list1 = ["a","a","b","b","c"]

list2 = [1, 3, 5, 7, 9]`

How can I slice the second list based on the first list (list1 is sorted by its values)?

Like [[1,3],[5,7],[9]]

My lists are very long so I am looking for a fast way to precess this. Thanks!

Upvotes: 0

Views: 532

Answers (2)

RoadRunner
RoadRunner

Reputation: 26325

You could also just use a dictionary:

from collections import defaultdict

list1 = ["a","a","b","b","c"]
list2 = [1, 3, 5, 7, 9]

d = defaultdict(list)
for k, v in zip(list1, list2):
    d[k].append(v)

>>> print([lst for lst in sorted(d.values())])
[[1, 3], [5, 7], [9]]

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799110

With itertools.groupby() and a bit of effort.

>>> [[b[1] for b in r] for p,r in itertools.groupby(zip(list1, list2), operator.itemgetter(0))]
[[1, 3], [5, 7], [9]]

Use itertools.izip() instead of zip() if you're running 2.x.

Upvotes: 2

Related Questions