将列表拆分为通过分组另一个列表确定的组

时间:2014-04-24 13:56:55

标签: python list grouping

说我有两个清单

a = [True, True, True, False, False, True, False]
b = [1, 2, 1, 3, 2, 1, 0]

我可以将一个列表分组为类似的项目:

import itertools
b =  [list(g) for k, g in itertools.groupby(a)]
>>> [[True, True, True], [False, False], [True], [False]] 

是否有一种方便的方法将此操作应用于其他列表以提供:

>>> [[1,2,1], [3,2], [1], [0]]

这有效,但有更好的东西:?

new_list = []
index = 0
for i in b:
    length = len(i)
    new_list.append(y[index:index+length])
    index += length

由于

2 个答案:

答案 0 :(得分:2)

您可以groupby上的enumerate(a)

>>> from itertools import groupby
>>> from operator import itemgetter
>>> indices = ((x[0] for x in g) for _, g in groupby(enumerate(a), key=itemgetter(1)))
>>> [[b[x] for x in lst] for lst in indices]
[[1, 2, 1], [3, 2], [1], [0]]

答案 1 :(得分:1)

from itertools import groupby, izip
groups = [list(grp) for _, grp in groupby(izip(a, b), lambda x: x[0])]
print [[number for _, number in items] for items in groups]
# [[1, 2, 1], [3, 2], [1], [0]]