[英]Generating nested lists with specified lengths
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? 如何添加条件以告知python将随机值添加到列表中,直到达到指定长度? 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 *我宁愿不使用count + = 1
desired output: 所需的输出:
shape [[0],[0,1,0],[1,1,0,1,0],[1,0,0,0,1,1,0]...etc]
形状[[0],[0,1,0],[1,1,0,1,0],[1,0,0,0,1,1,0] ...等]
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. [someFunc()] * someNum
在于,Python在执行外部表达式之前先评估内部表达式someFunc()
并将其解析为某个数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.