How to create a number of empty nested lists in py

2019-01-23 08:51发布

This question already has an answer here:

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 a to determine it. I thought about simple my_variable=[[]]*a, but that creates copies of lists and it is not what I want to have.

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?

2条回答
Summer. ? 凉城
2楼-- · 2019-01-23 09:07
>>>[[] 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.

查看更多
迷人小祖宗
3楼-- · 2019-01-23 09:19

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 xrange was removed, you will want this:

lst = [[] for _ in range(a)]
查看更多
登录 后发表回答