Python打印从000-111的所有二进制数字

时间:2018-12-29 13:37:24

标签: python performance binary

我需要以字符串形式生成000-111中的所有二进制数,而我的第一种方法如下所示。但是,令我震惊的是,这必须是一种非常低效的方法。请问有没有更好的方法,它们如何更有效?

 # print all binary numbers from 000 - 111
    for i in range(2):
        for j in range(2):
            for k in range(2):
                value = f'{i}{j}{k}'
                print(value)

3 个答案:

答案 0 :(得分:2)

您可以这样做:

for i in range(8):
    s = bin(i)[2:]
    print(s.zfill(3))

输出

000
001
010
011
100
101
110
111

答案 1 :(得分:1)

您可以使用它;

>>> ['{:03b}'.format(i) for i in range(8)]
['000', '001', '010', '011', '100', '101', '110', '111']

>>> ['{:03b}'.format(i) for i in range(2,8)]
['010', '011', '100', '101', '110', '111']

只需将范围转换为十进制即可。

答案 2 :(得分:0)

有几种不同的方法以及它们的结果。在总体方案中,性能差异很小,因此您不必担心太多。

%%timeit
for i in range(2):
    for j in range(2):
        for k in range(2):
            value = f'{i}{j}{k}'
            print(value)

原始结果:823 µs ± 49.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%%timeit
for i in range(8):
    print("{0:03b}".format(i))

结果:784 µs ± 35.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%%timeit  
for i in range(8):    
    print(bin(i)) #note that this does not produce the output exactly as you'd want it

结果:807 µs ± 36.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%%timeit 
for i in range(8): 
    print(bin(i)[2:].rjust(3, '0')) #this one really surprised me, i didn't expect it to be fastest.

结果:773 µs ± 43.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

如果您不想使用二进制表示形式,则只是itertools版本。请注意,为了进行比较,我已排除了库导入。

from itertools import product
bits = ['0', '1']
%%timeit
for i in product(bits, repeat = 3):
    print(''.join(i))

结果:801 µs ± 65.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)