I would like to turn this list of booleans:
bool_list: [False, False, True, False, False, True, False, True, True, False]
Into this list of integers:
int_li = [0, 0, 1, 1, 1, 2, 2, 3, 4, 4]
Basicaly, iterate through the list of booleans and incremente 1 everytime the value is True. Any efficient way to do that ?
CodePudding user response:
If you have Python 3.8 or later, you could make use of the walrus operator to generate your desired result using a list comprehension, making use of the fact that in an integer context, True == 1
and False == 0
:
v = 0
int_li = [v := v b for b in bool_list]
Output:
[0, 0, 1, 1, 1, 2, 2, 3, 4, 4]
CodePudding user response:
Create a variable (e.g. count
with a value of 0, loop through each item in the list and every time it is True
, add 1 to count
. Then append count
to the new list like so:
bool_list = [False, False, True, False, False, True, False, True, True, False]
int_li = []
count = 0
for item in bool_list:
if item:
count = 1
int_li.append(count)
print(int_li)
# [0, 0, 1, 1, 1, 2, 2, 3, 4, 4]
CodePudding user response:
from itertools import accumulate
int_li = list(map(int, accumulate(bool_list)))
As Daniel Hao pointed out, pure accumulate
doesn't work, as the first element will remain bool
, resulting in [False, 0, 1, 1, 1, 2, 2, 3, 4, 4]
.
Mapping to int
is the simplest fix I saw, though I don't like it much.
Another way, with an initial 0 that we then disregard:
from itertools import accumulate
_, *int_li = accumulate(bool_list, initial=0)
CodePudding user response:
simply do this with list comprehension in one line:
bool_list = [False, False, True, False, False, True, False, True, True, False]
int_list = [sum(bool_list[:i 1]) for i in range(len(bool_list))]
output:
[0, 0, 1, 1, 1, 2, 2, 3, 4, 4]