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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14931769/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:53:31  来源:igfitidea点击:

How to get all combination of n binary value?

pythonlistmathpython-2.7

提问by LWZ

In Python, how can I get all combinations of nbinary values 0and 1?

在 Python 中,如何获得n二进制值0和的所有组合1

For example, if n = 3, I want to have

例如,如果n = 3,我想要

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

How can I do this?

我怎样才能做到这一点?

采纳答案by Volatility

Use itertools.product

itertools.product

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

This will yield a list of tuples (see here)

这将产生一个元组列表(见这里

You can easily change this to use a variable repeat:

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

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

If you need a list of lists, then you can use the mapfunction (thanks @Aesthete).

如果您需要列表列表,则可以使用该map功能(感谢@Aesthete)。

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

Or in Python 3:

或者在 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)]

Note that using mapor a list comprehension means you don't need to convert the product into a list, as it will iterate through the itertools.productobject and produce a list.

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

回答by MoveFast

Following will give you all such combinations

以下将为您提供所有此类组合

bin = [0,1]
[ (x,y,z) for x in bin for y in bin for z in bin ]

回答by Anil

Without using any in-build functions or smart techniques we can get like this.

无需使用任何内置函数或智能技术,我们就可以得到这样的结果。

def per(n):
    for i in range(1<<n):
        s=bin(i)[2:]
        s='0'*(n-len(s))+s
        print (map(int,list(s)))
per(3)       

output

输出

[0, 0, 0]
[0, 0, 1]
[0, 1, 0]
[0, 1, 1]
[1, 0, 0]
[1, 0, 1]
[1, 1, 0]
[1, 1, 1]