将元素分组到列表中

Pet*_*ter 1 python python-itertools python-3.x

我想根据索引将元素分组到列表列表中,从数据中的第一个位置开始,直到下一个 False。这就是一个分组。继续直到最后一个元素。

data = ['a','b','c','d','e','f'] 
indexer = [True, True, False, False, True, True]
Run Code Online (Sandbox Code Playgroud)

结果将是:

[['a','b','c'], ['d'], ['e','f'] ]
Run Code Online (Sandbox Code Playgroud)

itertools groupby 是正确的解决方案吗?我对如何实现它有点困惑。

Dan*_*ejo 5

accumulate然后使用groupby

from itertools import groupby, accumulate
from operator import itemgetter

data = ['a', 'b', 'c', 'd', 'e', 'f']
indexer = [True, True, False, False, True, True]


groups = accumulate((not b for b in indexer), initial=0)
res = [[v for _, v in vs] for k, vs in groupby(zip(groups, data), key=itemgetter(0))]
print(res)
Run Code Online (Sandbox Code Playgroud)

输出

[['a', 'b', 'c'], ['d'], ['e', 'f']]
Run Code Online (Sandbox Code Playgroud)

在您的特定示例中,变量组相当于:

[0, 0, 0, 1, 2, 2, 2]  # print(list(groups))
Run Code Online (Sandbox Code Playgroud)

这个想法是每次遇到一个值时更改组IDFalse,因此需要否定它。

作为替代方案,您可以使用 @Matiiss 想法的变体(全部归功于他):

res, end = [], True
for d, i in zip(data, indexer):
    if end:
        res.append([])
    res[-1].append(d)
    end = not i

print(res)
Run Code Online (Sandbox Code Playgroud)

注意:在Python中,您可以直接对布尔值求和,因为它们是整数

  • 哇这太聪明了! (2认同)