我想生成一个带有模式的位列表,代码是这样的:
sublist = [1] * N_SUBBITS
sublist[0] = 0
bits = sublist * N_SUBLISTS
如果N_SUBBITS = 4
和N_SUBLISTS = 3
,这会生成如下列表:
[0, 1, 1 ,1, 0, 1, 1, 1, 0, 1, 1, 1]
可以用一个表达式来写吗?
我想生成一个带有模式的位列表,代码是这样的:
sublist = [1] * N_SUBBITS
sublist[0] = 0
bits = sublist * N_SUBLISTS
如果N_SUBBITS = 4
和N_SUBLISTS = 3
,这会生成如下列表:
[0, 1, 1 ,1, 0, 1, 1, 1, 0, 1, 1, 1]
可以用一个表达式来写吗?
这会吗?
In [4]: [1 if x % N_SUBBITS else 0 for x in range(N_SUBBITS * N_SUBLISTS)]
Out[4]: [0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1]
另一个:
In [15]: [1 if x else 0 for l in range(N_SUBLISTS) for x in range(N_SUBBITS)]
Out[15]: [0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1]
变化:
[x % N_SUBBITS and 1 for x in range(N_SUBBITS * N_SUBLISTS)]
[x and 1 for l in range(N_SUBLISTS) for x in range(N_SUBBITS)]
怎么样:
>>> N_SUBBITS = 4
>>> N_SUBLISTS = 3
>>> ([0] + [1]*(N_SUBBITS-1)) * N_SUBLISTS
[0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1]