简体   繁体   English

为每个 for 循环创建一个新列表

[英]Creating a new list for each for loop

I wish to create a new list each time a for loop runs我希望每次 for 循环运行时创建一个新列表

#Reading user input e.g. 10
lists = int(raw_input("How many lists do you want? "))
for p in range(0,pooled):
    #Here I want to create 10 new empty lists: list1, list2, list3 ...

Is there any smart way of doing this?有什么聪明的方法可以做到这一点吗?

Thanks,谢谢,

Kasper卡斯帕

Use a list comprehension:使用列表推导:

num_lists = int(raw_input("How many lists do you want? "))
lists = [[] for i in xrange(num_lists)]

The easiest way is to create a list of lists:最简单的方法是创建一个列表列表:

   num_lists = int(raw_input("How many lists do you want? "))
   lists = []
   for p in range(num_lists):
        lists.append([])

Then you can access, for example, list 3 with list[2] , and the ith item of list 3 with list[2][i] .例如,您可以使用list[2]访问列表 3,使用list[2][i]访问列表 3 的第 i 个项目。

perhaps in your situation you could use a defaultdict?也许在您的情况下您可以使用默认字典?

>>> from collections import defaultdict
>>> m=defaultdict(list)
>>> m
defaultdict(<type 'list'>, {})
>>> for i in range(5):
...     len(m[i])
... 
0
0
0
0
0
>>> m
defaultdict(<type 'list'>, {0: [], 1: [], 2: [], 3: [], 4: []})

To create our lists we generate names on the fly and assign them an empty list:为了创建我们的列表,我们动态生成名称并为其分配一个空列表:

lists = int(input("How many lists do you want? "))
varname = 'list'
for i in range(lists):
    exec(f"{varname}{i} = []")
exec(f'print(f"list{lists-1} is", list{lists-1})')
# list9 is []

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM