Python:创建多个列表

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

Python : creating multiple lists

pythonlistpython-2.7python-3.x

提问by zathizh

I'm trying to create multiple lists like the following:

我正在尝试创建多个列表,如下所示:

l1 = []  
l2 = []  
..  
ln = []  

Is there any way to do that?

有没有办法做到这一点?

采纳答案by A.J. Uppal

What you can do is use a dictionary:

你可以做的是使用字典:

>>> obj = {}
>>> for i in range(1, 21):
...     obj['l'+str(i)] = []
... 
>>> obj
{'l18': [], 'l19': [], 'l20': [], 'l14': [], 'l15': [], 'l16': [], 'l17': [], 'l10': [], 'l11': [], 'l12': [], 'l13': [], 'l6': [], 'l7': [], 'l4': [], 'l5': [], 'l2': [], 'l3': [], 'l1': [], 'l8': [], 'l9': []}
>>> 

You can also create a list of lists using list comprehension:

您还可以使用列表理解创建列表列表:

>>> obj = [[] for i in range(20)]
>>> obj
[[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []]
>>> 

回答by huu

Create a list of lists:

创建列表列表:

lists = []
n = 20
for i in range(n):
    lists.append([])

print lists[0] # Prints []
print lists[19] # Prints []

回答by Akhzar Farhan

You can simply use a for loop to create n lists.

您可以简单地使用 for 循环来创建 n 个列表。

for i in range(10): a_i = [i] #Stores the corresponding value of i in each a_i list. print(a_i)

for i in range(10): a_i = [i] #Stores the corresponding value of i in each a_i list. print(a_i)

The variable a_i changes as i increments, so it becomes a_1, a_2, a_3 ... and so on.

变量 a_i 随着 i 的增加而变化,所以它变成了 a_1、a_2、a_3……等等。

回答by Cindyleee

You can use dictionary comprehension:

您可以使用字典理解:

obj = {i:[] for i in list(range(1,5))}

回答by Sanan Guliyev

Single line:

单线:

>>> lists = [[]] * 3
>>> lists[0]
[]