简体   繁体   English

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

[英]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.

相关问题 将不同长度的列表嵌套到 pandas 数据帧中 - Nested lists of differing lengths into pandas data frame 生成由动态长度列表组成的动态长度列表 - Generating a list of dynamic length consisting of lists of dynamic lengths 使用函数从指定索引处开始在Python中汇总不同长度的列表 - Summing lists of different lengths in Python beginning at a specified index using a function Lambda函数获取嵌套列表中所有列表的长度总和? - Lambda function to get the sum of lengths of all the lists in a nested list? 从嵌套的不等长度列表中创建一个pandas数据帧 - Create a pandas dataframe from a nested lists of unequal lengths 从XML文档生成嵌套列表 - Generating nested lists from XML doc 从Python中的嵌套编号列表生成XML - Generating XML from nested numbered lists in Python 从列表列表生成嵌套字典 - Generating a nested dictionary from a list of lists 如何将两个相等长度的列表转换为表示有序对的嵌套列表列表? - How can I turn two lists of equal lengths into a list of nested lists that represent ordered pairs? 当嵌套列表的长度不同或缺少元素时,如何对 python 中的嵌套列表进行排序? - How to sort a nested list in python when the nested lists have different lengths or missing elements?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM