2

我想生成一个带有模式的位列表,代码是这样的:

sublist = [1] * N_SUBBITS
sublist[0]  = 0 
bits = sublist * N_SUBLISTS

如果N_SUBBITS = 4N_SUBLISTS = 3,这会生成如下列表:

[0, 1, 1 ,1, 0, 1, 1, 1, 0, 1, 1, 1]

可以用一个表达式来写吗?

4

2 回答 2

3

这会吗?

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)]
于 2013-04-07T22:37:03.047 回答
3

怎么样:

>>> 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]
于 2013-04-07T22:38:50.557 回答