我想生成一个带有模式的位列表,代码如下:
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]
是否可以用单个表达式编写它?
答案 0 :(得分: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)]
答案 1 :(得分: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]