生成具有指定长度的嵌套列表

Ben*_*mes 1 python nested list python-2.7

我想生成一个列表列表,其中包含渐进数量的随机生成的二进制值.

如何添加一个条件告诉python将随机值添加到列表中,直到达到指定的长度?在这种情况下,每个新列表的长度应该是逐渐变大的奇数.

from random import randint  

shape = [] 
odds = [x for x in range(100) if x % 2 == 1]

while len(shape) < 300:
    for x in odds:
        randy = [randint(0,1)] * x ??  # need to run this code x amount of times 
        shape.append(randy)            # so that each len(randy) = x
Run Code Online (Sandbox Code Playgroud)

*我宁愿不使用count + = 1

期望的输出:

形状[[0],[0,1,0],[1,1,0,1,0],[1,0,0,0,1,1,0] ......等]

Joe*_*ett 5

你想要一个生成器表达式 列表理解:

randy = [randint(0, 1) for i in range(x)]
Run Code Online (Sandbox Code Playgroud)

问题[someFunc()] * someNum是Python首先计算内部表达式,someFunc()并在执行外部表达式之前将其解析为某个数字.