简体   繁体   English

递增存储为布尔值列表的数字

[英]Increment a number stored as a list of booleans

In this example I'm iterating over all possible variations of a mask, which I store as a list of booleans 在此示例中,我遍历了掩码的所有可能变体,并将其存储为布尔值列表

Nmax = 32
for num in range (2**Nmax):
    bool_list = [bool(num & (1<<n)) for n in range(Nmax)]
    # other stuff

However, the operation to generate bool_list is a bit of a bottleneck in the code - the rest is rather fast matrix multiplication. 但是,生成bool_list的操作在代码中有点瓶颈-剩下的就是相当快的矩阵乘法。 Is there a faster way to increment the number stored in bool_list than I'm doing? 有没有一种比我正在执行的更快的方法来增加存储在bool_list的数字?

You're just taking all combinations of (False, True) Nmax times. 您只是在使用(False,True) Nmax次的所有组合。 Hence, 因此,

from itertools
print(list(itertools.product(*[(False, True)]*Nmax)))

will display all the masks. 将显示所有蒙版。

If you want to use it while iterating, 如果您想在迭代时使用它,

Nmax = 32
masks = itertools.product(*[(False, True)]*Nmax)
for mask in masks:
    # Do stuff

Note that mask will be a tuple rather than a list. 请注意, mask将是一个元组而不是一个列表。

For one, I think you can precompute the shifts: 首先,我认为您可以预先计算这些变化:

Nmax = 32
shifts = [(1 << n) for n in range(Nmax)]
for num in range(2**Nmax):
    bool_list = [bool(num & shift) for shift in shifts]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM