2013-02-26 53 views
1

我想生成一個列表,其中包含漸進數量的隨機生成的二進制值。生成具有指定長度的嵌套列表

如何添加一個條件,告訴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 

*我寧願不使用count + = 1

期望的輸出:

形狀 [[0],[0,1,0], [1,1,0,1,0],[1,0,0,0,1,1,0] ... etc]

+1

如果x%2 == 1''變爲'賠率= [x for range in(1,100,2)]'',則賠率= [x for範圍(100)它使用從1到100的一系列奇數(2是「step」或「interval」)。 – 2013-02-26 21:41:52

+0

+1好點。我會用它。 – 2013-02-26 21:57:48

回答

5

你想要一個發電機表達列表理解

randy = [randint(0, 1) for i in range(x)] 

的問題[someFunc()] * someNum就是,Python首先計算內表達,someFunc()和執行外表達式之前它解決一些數字。

+0

很好做...所以這實際上是一個謂詞列表理解? – 2013-02-26 21:57:15