Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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_List - Fatal编程技术网

Python 制作嵌套列表的最佳方法?

Python 制作嵌套列表的最佳方法?,python,list,Python,List,以下哪种方法是处理非常大的列表的最佳方法 >>> nested_list=[ [0 for x in xrange(10)] for y in xrange(10)] >>> nested_list=[ [0]*10]*20 >>> nested_list=[] >>> for x in xrange(20): .... for y in xrange(10):

以下哪种方法是处理非常大的列表的最佳方法

    >>> nested_list=[ [0 for x in xrange(10)] for y in xrange(10)]
    >>>  nested_list=[ [0]*10]*20
    >>>  nested_list=[]
    >>>  for x in xrange(20):
    ....     for y in xrange(10):
     ....        nested_list.append([0])

一般而言,您应小心以下各项的构造:

>>> li=[[None]*3]*3
>>> li
[[None, None, None], [None, None, None], [None, None, None]]
因为您已将多个引用复制到同一对象。修改一个:

>>> li[0][1]=True
对于Python新手来说,您有时会以一种令人惊讶的方式修改所有内容:

>>> li
[[None, True, None], [None, True, None], [None, True, None]]
请注意,所有嵌套列表的中间元素都会随着赋值li[0][1]=True而更改

其他方法正在创建不同类型的嵌套:

>>> nli=[ [None for x in xrange(3)] for y in xrange(4)]
>>> nli
[[None, None, None], [None, None, None], [None, None, None], [None, None, None]]
>>> nli[0][1]=True
>>> nli
[[None, True, None], [None, None, None], [None, None, None], [None, None, None]]

注意,正如预期的那样,nli[0][1]=True的赋值只改变了一个元素,这取决于它是否是可变或不可变对象的嵌套列表……这是一个非常模糊的问题。。。你想要什么样的清单?随机数?numpy.zeros20,10,1@dawg假设对象是可变的?[[0代表xrange10中的x]代表xrange10中的y]很可能是您想要的。。。