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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19249201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:14:47  来源:igfitidea点击:

How to create a number of empty nested lists in python

pythonlistnested-lists

提问by Andy S. C.

I want to have a variable that is a nested list of a number of empty lists that I can fill in later. Something that looks like:

我想要一个变量,它是多个空列表的嵌套列表,我可以稍后填写。看起来像的东西:

my_variable=[[], [], [], []]

However, I do not know beforehand how many lists I will need, only at the creation step, therefore I need a variable ato determine it. I thought about simple my_variable=[[]]*a, but that creates copies of lists and it is not what I want to have.

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

I could do:

我可以:

my_variable=[]  
for x in range(a):
   my_variable.append([])

but I'm looking for a more elegant solution (preferably one-liner). Is there any?

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

采纳答案by Andy S. C.

Try a list comprehension:

尝试列表理解

lst = [[] for _ in xrange(a)]

See below:

见下文:

>>> 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], [], [], [], [], [], [], [], [], []]
>>>

Note however that the above is for Python 2.x. On Python 3.x., since xrangewas removed, you will want this:

但请注意,以上内容适用于 Python 2.x。在 Python 3.x. 上,因为xrange被删除了,你会想要这个:

lst = [[] for _ in range(a)]

回答by Nullify

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

Edit :-

编辑 :-

[[]]*10

This will give you the same result like above but the list are not distinct instances,they are just n references to the same instance.

这将为您提供与上面相同的结果,但列表不是不同的实例,它们只是对同一实例的 n 个引用。