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

时间:2014-08-20 05:04:32

标签: 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.append([0])

1 个答案:

答案 0 :(得分: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

的分配只会改变一个元素