Python - 另一个列表中符合条件的元素的索引列表
Python - List of indices of elements of another list that match a condition
这看起来很简单,但我有点卡在这上面了。
我有一个逻辑值列表,例如:
a=[True, False, True, True, False, False, True, True, True]
我想构建另一个列表,其中包含(在子列表中)'a' 的索引 'True',连续的索引放在同一个子列表中。所以,对于上面的例子,答案是:
[[0], [2,3], [6,7,8]]
使用itertools.groupby
and enumerate
,一行是可能的:
from itertools import groupby
[[i for i, _ in g] for k, g in groupby(enumerate(a), key=lambda x: x[1]) if k]
同理,
>>> a = [True, False, True, True, False, False, True, True, True]
>>> from itertools import groupby
>>> [list(v) for k,v in groupby([_ if a[_] else None for _ in range(len(a)) ], lambda x: not x is None) if k]
[[0], [2, 3], [6, 7, 8]]
纯 Python,无库:
a=[True, False, True, True, False, False, True, True, True]
indcs = [i for i, b in enumerate(a) if b]
if indcs:
o, s = [], [indcs[0]]
for a, b in zip(indcs, indcs[1:] + [indcs[-1]]):
if b-a == 1:
s.append(b)
else:
o.append(s)
s = [b]
else:
o = []
o
Out[32]: [[0], [2, 3], [6, 7, 8]]
这看起来很简单,但我有点卡在这上面了。
我有一个逻辑值列表,例如:
a=[True, False, True, True, False, False, True, True, True]
我想构建另一个列表,其中包含(在子列表中)'a' 的索引 'True',连续的索引放在同一个子列表中。所以,对于上面的例子,答案是:
[[0], [2,3], [6,7,8]]
使用itertools.groupby
and enumerate
,一行是可能的:
from itertools import groupby
[[i for i, _ in g] for k, g in groupby(enumerate(a), key=lambda x: x[1]) if k]
同理,
>>> a = [True, False, True, True, False, False, True, True, True]
>>> from itertools import groupby
>>> [list(v) for k,v in groupby([_ if a[_] else None for _ in range(len(a)) ], lambda x: not x is None) if k]
[[0], [2, 3], [6, 7, 8]]
纯 Python,无库:
a=[True, False, True, True, False, False, True, True, True]
indcs = [i for i, b in enumerate(a) if b]
if indcs:
o, s = [], [indcs[0]]
for a, b in zip(indcs, indcs[1:] + [indcs[-1]]):
if b-a == 1:
s.append(b)
else:
o.append(s)
s = [b]
else:
o = []
o
Out[32]: [[0], [2, 3], [6, 7, 8]]