【问题标题】:Get a list of all possible binary tuples with length n获取长度为 n 的所有可能二进制元组的列表
【发布时间】:2016-02-10 11:27:02
【问题描述】:

我需要一个函数,它返回所有可能的二进制元组的列表,长度为 n,如下所示:

binaryTuples(n=2) =>  [(0,0),(0,1),(1,0),(1,1)]
binaryTuples(n=3) =>  [(0,0,0),(0,0,1),(0,1,1),(1,1,1) ... and so on]

我知道这可以通过itertools 完成,但我不知道怎么做。

【问题讨论】:

    标签: python tuples itertools


    【解决方案1】:

    试试:

    itertools.product(*[(0, 1)] * n)
    

    其中n 是所需的大小。

    例子:

    import itertools
    print "For n = 2: " + str(list(itertools.product(*[(0, 1)] * 2)))
    print "For n = 3: " + str(list(itertools.product(*[(0, 1)] * 3)))
    

    输出:

    For n = 2: [(0, 0), (0, 1), (1, 0), (1, 1)]                                                                                                                      
    For n = 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)]  
    

    您可以实时运行它here

    我受到generating binary numbers of size n as tuples : itertools.product(*[(0, 1)] * n) 的启发,但没有标记为重复,因为它不是您想要的。 ;)

    【讨论】:

    • 正是我需要的,我会尽快将其标记为答案。
    【解决方案2】:

    使用itertools.product 是明智的做法。不过 gsamaras 的代码可以稍微清理一下:

    import itertools
    
    def binary_tuples(w):
        return itertools.product((0, 1), repeat=w)
    
    print(list(binary_tuples(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)]
    

    只是为了好玩,这里是使用str.format 方法的方法,它可以将整数格式化为二进制。诀窍是将所需的位串长度传递到格式规范字符串中。

    此代码在 Python 2.6 及更高版本上运行,尽管更高版本可以简化格式规范字符串。当然,在 Python 3 上,您需要将 xrange 更改为 range

    def binary_tuples(w):
        return [tuple(int(d) for d in '{0:0{1}b}'.format(i, w))
            for i in xrange(1<<w)]
    
    print(binary_tuples(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)]
    

    这是一个生成器版本:

    def binary_tuples_gen(w):
        for i in xrange(1<<w):
            yield tuple(int(d) for d in '{0:0{1}b}'.format(i, w))
    
    for t in binary_tuples_gen(3):
        print(t)
    

    输出

    (0, 0, 0)
    (0, 0, 1)
    (0, 1, 0)
    (0, 1, 1)
    (1, 0, 0)
    (1, 0, 1)
    (1, 1, 0)
    (1, 1, 1)
    

    【讨论】:

      猜你喜欢
      • 2021-04-06
      • 2021-02-22
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 2011-12-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多