如何获得n个二进制值的所有组合? [英] How to get all combination of n binary value?
本文介绍了如何获得n个二进制值的所有组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Python中,如何获取n
二进制值0
和1
的所有组合?
In Python, how can I get all combinations of n
binary values 0
and 1
?
例如,如果n = 3
,我想拥有
[ [0,0,0], [0,0,1], [0,1,0], [0,1,1], ... [1,1,1] ] #total 2^3 combinations
我该怎么做?
推荐答案
import itertools
lst = list(itertools.product([0, 1], repeat=3))
这将产生一个元组列表(请参见此处)
This will yield a list of tuples (see here)
您可以轻松地将其更改为使用变量repeat
:
You can easily change this to use a variable repeat
:
n = 3
lst = list(itertools.product([0, 1], repeat=n))
如果需要列表列表,则可以使用map
函数(感谢@Aesthete).
If you need a list of lists, then you can use the map
function (thanks @Aesthete).
lst = map(list, itertools.product([0, 1], repeat=n))
或者在Python 3中:
Or in 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
对象并生成列表.
Note that using map
or a list comprehension means you don't need to convert the product into a list, as it will iterate through the itertools.product
object and produce a list.
这篇关于如何获得n个二进制值的所有组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文