【问题标题】:How to get all combination of n binary value? [duplicate]如何获得n个二进制值的所有组合? [复制]
【发布时间】:2013-02-02 14:47:10
【问题描述】:

在 Python 中,如何获取 n 二进制值 01 的所有组合?

比如n = 3,我想拥有

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

我该怎么做?

【问题讨论】:

标签: python list math python-2.7


【解决方案1】:

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

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)       

输出

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

【讨论】:

  • “0x000001b30c760128>
  • 必须调用 (list(map...)) 才能获取实际列表
  • 好主意!这是一个带有格式函数的简单版本:``` def per(n): for i in range(1>> per(3)
【解决方案2】:

使用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 对象并生成一个列表。

【讨论】:

  • +1 - map(list, product([0, 1], repeat=3)) 将返回相同的格式以防 OP 感兴趣。
  • 这很好,元组也可以。
  • @Volatility,只是好奇,你怎么知道的?我不知道如何从 Python 文档中找到这个函数。
  • @LWZ 它comes with experience。 (见第 6 点)
  • @Volatility,多么棒的帖子,谢谢!
【解决方案3】:

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

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

【讨论】:

  • 他仅以n=3 为例,因此他希望将其参数化。
  • 这可行,但 n 不能很大...
  • 这不会扩展!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-10
  • 2020-12-30
  • 2020-09-17
  • 2016-07-18
  • 2016-04-23
  • 2014-07-08
相关资源
最近更新 更多