使用多个列表乘法运算符紧凑生成单个列表

时间:2013-04-07 22:33:46

标签: python

我想生成一个带有模式的位列表,代码如下:

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]

是否可以用单个表达式编写它?

2 个答案:

答案 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]