Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将元素追加到展开列表中_Python_Python 3.x - Fatal编程技术网

Python 将元素追加到展开列表中

Python 将元素追加到展开列表中,python,python-3.x,Python,Python 3.x,我想生成一个展开的嵌套列表。如何生成这样的嵌套列表 [1.0, None] [-1.0, [1.0, None]] [-1.0, [1.0, [3.0, None]]] [6,[-1.0, [1.0, [3.0, None]]]] 本质上,我想创建一个嵌套列表,其中每个元素都被插入到原始列表中 似乎将新元素添加到列表的第一个元素,并将前一个元素作为子列表: l = [1.0, None] new = [-1.0] new.append(l) 然后,new将是: [-1.0, [1.0, No

我想生成一个展开的嵌套列表。如何生成这样的嵌套列表

[1.0, None]
[-1.0, [1.0, None]]
[-1.0, [1.0, [3.0, None]]]
[6,[-1.0, [1.0, [3.0, None]]]]

本质上,我想创建一个嵌套列表,其中每个元素都被插入到原始列表中

似乎将新元素添加到列表的第一个元素,并将前一个元素作为子列表:

l = [1.0, None]
new = [-1.0]
new.append(l)
然后,
new
将是:

[-1.0, [1.0, None]]

你可以这样做:

import random

l = [-1.0, None]

for i in range(10):        
    l = [random.randint(0, 10), l]

print(l)

您只需将原始列表包装到另一个列表中。

我建议您为此功能创建一个类。您可以使用的模板包括:

class nestlist:
    def __init__(self,startlist=[]):
        self.nestlist=startlist
    def get(self):
        return self.nestlist
    def add(self,x):
        self.nestlist = [x,self.nestlist]
    def pop(self):
        popval = self.nestlist[0]
        self.nestlist = self.nestlist[1]
        return popval

nl = nestlist()
nl.add(1)
nl.add(-1)
nl.add(6)

print(nl.get())
这将创建类,并根据您的示例添加1、-1和6。调用get()时,它根据需要返回[6、[-1、[1、[]]]。我还添加了一个类似的“pop”函数来演示在扩展这个概念时使用类是如何有益的