给定的最大列表l
大小为整数r
与N
位,怎么做我创建大小r*N
列表binaryL
其中的值反映的l
正位?扩展整数列表1 - 外的n个二进制列表
实施例,用于N=2
位:
l = [1, 0, 3] --> [01, 00, 11] (in bits)
变得
binaryL = [0, 0, 1, 1, 0, 1]
,其中每个组的r
整数等于每个比特。换句话说,第一个0, 0, 1
是l
的第一位,最后的1, 0, 1
是l
的最后一位。
另一种选择是只获得在它们的顺序的比特,其中
binaryL = [0, 1, 0, 0, 1, 1]
在这种情况下,每个值被转换为它的比特。
对于那些想了解一下性能,
import random
from itertools import chain
import time
N=8
l=[random.randrange(1,2**N,1) for _ in range (10000000)]
r=len(l)
a = time.clock()
res1 = []
for i in l:
res1 += [int(b) for b in "{0:b}".format(i).rjust(N, '0')]
b = time.clock()
res2 = list(map(int, chain.from_iterable(bin(i)[2:].zfill(N) for i in l)))
c = time.clock()
res3 = list(map(int, ''.join(bin(i)[2:].zfill(N) for i in l)))
d = time.clock()
res4 = [0] * N * r
for ind, binary in enumerate(map(bin, l)):
for ind_bit, bit in enumerate(binary[2:].zfill(N)):
res4[r * ind_bit + ind] = int(bit)
e = time.clock()
res5 = list(map(int, chain.from_iterable(zip(*[bin(i)[2:].zfill(N) for i in l]))))
f = time.clock()
# res1, res2 and res3 are show bits by value. res4 and res5 shows bits by index
print(res1==res2)
print(res2==res3)
print(res4==res5)
print(b-a)
print(c-b)
print(d-c)
print(e-d)
print(f-e)
打印为1000个值:
True
True
True
0.003963000000000001 # neverwalkaloner
0.0025400000000000006 # Psidom1
0.0023320000000000007 # Psidom2
0.004358000000000001 # Rockybilly
0.0021629999999999983 # Psidom3
和10.000.000值
True
True
True
36.333539 # neverwalkaloner
25.674224000000002 # Psidom1
24.49611499999999 # Psidom2
47.370771000000005 # Rockybilly
66.25204 # Psidom3
为什么'[01,00,11]'变成'[0,0,1,1,0,1]'而不是'[0,1,0,0,1,1]'? –
为清晰起见编辑 – BlueMoon93