Python 如何创建空列表列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33990673/
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 14:17:23  来源:igfitidea点击:

How to create a list of empty lists

pythonlist

提问by daemon_headmaster

Apologies if this has been answered before, but I couldn't find a similar question on here.

抱歉,如果之前已经回答过这个问题,但我在这里找不到类似的问题。

I am pretty new to Python and what I am trying to create is as follows:

我对 Python 很陌生,我要创建的内容如下:

list1 = []
list2 = []
results = [list1, list2]

This code works absolutely fine, but I was wondering if there was a quicker way to do this in one line.

这段代码工作得很好,但我想知道是否有一种更快的方法可以在一行中做到这一点。

I tried the following, which didn't work, but I hope it demonstrates the sort of thing that I'm after:

我尝试了以下操作,但没有用,但我希望它展示了我所追求的东西:

result = [list1[], list2[]]

Also, in terms of complexity, would having it on one line really make any difference? Or would it be three assignments in either case?

此外,就复杂性而言,将它放在一条线上真的会有什么不同吗?或者在任何一种情况下都是三个任务?

采纳答案by Dawny33

For manually creating a specified number of lists, this would be good:

对于手动创建指定数量的列表,这会很好:

empty_list = [ [], [], ..... ]

In case, you want to generate a bigger number of lists, then putting it inside a for loop would be good:

如果你想生成更多的列表,那么把它放在 for 循环中会很好:

empty_lists = [ [] for _ in range(n) ]

回答by dietbacon

If you want a one-liner you can just do:

如果你想要一个单线你可以这样做:

result = [[],[]]

回答by roeland

For arbitrary length lists, you can use [ [] for _ in range(N) ]

对于任意长度的列表,您可以使用 [ [] for _ in range(N) ]

Do notuse [ [] ] * N, as that will result in the list containing the same list objectNtimes

不要使用[ [] ] * N,因为这将导致列表包含相同的列表对象N时间

回答by Michael

results = [[],[]]

or

或者

results = [list(), list()]

回答by Sina Safarabadi

I would suggest using numpy because you can build higher-dimensional list of lists as well:

我建议使用 numpy,因为您也可以构建更高维的列表列表:

import numpy as np
LIST = np.zeros( [2,3] )# OR np.zeros( [2,3,6] )

It works in any number of dimensions.

它适用于任意数量的维度。