Reputation: 961
I want to generate a list of lists that contains a progressive number of randomly generated binary values.
How do I add a condition that tells python to add random values to a list until it reaches a specified length? In this case, the length of each new list should be a progressively larger odd number.
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
*I would prefer to not use count += 1
desired output:
shape [[0],[0,1,0],[1,1,0,1,0],[1,0,0,0,1,1,0]...etc]
Upvotes: 1
Views: 143
Reputation: 24788
You want a generator expression list comprehension:
randy = [randint(0, 1) for i in range(x)]
The problem with [someFunc()] * someNum
is that Python first evaluates the inner expression, someFunc()
and resolves it to some number before executing the outer expression.
Upvotes: 5