如何在python中创建一些空的嵌套列表

And*_* C. 7 python list nested-lists

我想要一个变量,它是一个嵌套的列表,列出了一些我可以在以后填写的空列表.看起来像:

my_variable=[[], [], [], []]
Run Code Online (Sandbox Code Playgroud)

但是,我事先并不知道我需要多少列表,只是在创建步骤,因此我需要一个变量a来确定它.我想简单my_variable=[[]]*a,但是创建了列表的副本,这不是我想要的.

我可以:

my_variable=[]  
for x in range(a):
   my_variable.append([])
Run Code Online (Sandbox Code Playgroud)

但我正在寻找一种更优雅的解决方案(最好是单线).有没有?

iCo*_*dez 15

尝试列表理解:

lst = [[] for _ in xrange(a)]
Run Code Online (Sandbox Code Playgroud)

见下文:

>>> a = 3
>>> lst = [[] for _ in xrange(a)]
>>> lst
[[], [], []]
>>> a = 10
>>> lst = [[] for _ in xrange(a)]
>>> lst
[[], [], [], [], [], [], [], [], [], []]
>>> # This is to prove that each of the lists in lst is unique
>>> lst[0].append(1)
>>> lst
[[1], [], [], [], [], [], [], [], [], []]
>>>
Run Code Online (Sandbox Code Playgroud)

但请注意,上面的内容适用于Python 2.x. 在Python 3.x.上,自从xrange被删除后,你会想要这个:

lst = [[] for _ in range(a)]
Run Code Online (Sandbox Code Playgroud)


Nul*_*ify 7

>>>[[] for x in range(10)] #To make a list of n different lists, do this:
[[], [], [], [], [], [], [], [], [], []]
Run Code Online (Sandbox Code Playgroud)

编辑: -

[[]]*10
Run Code Online (Sandbox Code Playgroud)

这将给出与上面相同的结果,但列表不是不同的实例,它们只是对同一实例的n个引用.

  • 展示它与"[[]]*10`的区别是有帮助的 (4认同)
  • 考虑扩展您的答案,向提问者解释为什么这会达到预期的结果,可能链接到文档.原样,这只是一个有用的. (3认同)