你可以使用内置的bin
函数:
bin(8) #'0b1000'
获取列表:
[int(x) for x in bin(8)[2:]]
虽然似乎可能有更好的方法......
试一试:
>>> list('{0:0b}'.format(8))
['1', '0', '0', '0']
编辑 -- 哎呀,你想要整数:
>>> [int(x) for x in list('{0:0b}'.format(8))]
[1, 0, 0, 0]
又一次编辑 -
mgilson的版本稍微快一些:
$ python -m timeit "[int(x) for x in list('{0:0b}'.format(8))]"
100000 loops, best of 3: 5.37 usec per loop
$ python -m timeit "[int(x) for x in bin(8)[2:]]"
100000 loops, best of 3: 4.26 usec per loop
为了保持你最初的尝试精神:
binary = []
while num != 0:
bit = num % 2
binary.insert(0, bit)
num = num / 2
.reverse()
翻转列表前,先使用.append()
添加位而非在列表开头使用insert
。 - Tim