[英]Iterate through a list of booleans in order to create a new list of integers
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.基本上,遍历布尔值列表并在每次值为 True 时递增 1。 Any efficient way to do that ?
有什么有效的方法吗?
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
:如果您有 Python 3.8 或更高版本,则可以使用 walrus 运算符使用列表推导生成所需的结果,利用整数上下文中
True == 1
和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]
Create a variable (eg 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:创建一个变量(例如
count
值为 0,遍历列表中的每个项目,每次为True
时,将 +1 添加到count
。然后将count
附加到新列表,如下所示:
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]
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]
.正如 Daniel Hao 指出的那样,纯
accumulate
不起作用,因为第一个元素将保持bool
,导致[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.映射到
int
是我看到的最简单的修复,虽然我不太喜欢它。
Another way, with an initial 0 that we then disregard:另一种方式,初始 0 然后我们忽略:
from itertools import accumulate
_, *int_li = accumulate(bool_list, initial=0)
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.