gpt4 book ai didi

python - 如何获得n个二进制值的所有组合?

转载 作者:IT老高 更新时间:2023-10-28 22:20:12 25 4
gpt4 key购买 nike

在 Python 中,我怎样才能得到 n 二进制值 01 的所有组合?

比如如果n = 3,我想有

[ [0,0,0], [0,0,1], [0,1,0], [0,1,1], ... [1,1,1] ]  #total 2^3 combinations

我该怎么做?

最佳答案

使用 itertools.product

import itertools
lst = list(itertools.product([0, 1], repeat=3))

这将产生一个元组列表(参见 here)

您可以轻松地将其更改为使用变量repeat:

n = 3
lst = list(itertools.product([0, 1], repeat=n))

如果你需要一个列表列表,那么你可以使用 map 函数(感谢@Aesthete)。

lst = map(list, itertools.product([0, 1], repeat=n))

或者在 Python 3 中:

lst = list(map(list, itertools.product([0, 1], repeat=n)))
# OR
lst = [list(i) for i in itertools.product([0, 1], repeat=n)]

请注意,使用 map 或列表推导式意味着您不需要将产品转换为列表,因为它将遍历 itertools.product 对象和生成一个列表。

关于python - 如何获得n个二进制值的所有组合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14931769/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com