Python: Initialize a list of lists to a certain size,

耗尽温柔 提交于 2019-12-20 04:16:24

问题


I'm trying to initialize 'big_list', which is a list containing lists, and we know in advance that there will be 200 lists within 'big_list', and that each list will contain only strings or nothing, and that later in the program there will be a loop that appends(one or more times) to only a certain number of those lists.

Is there a simplest way to go about this?


回答1:


You can use list comprehension for example:

big_list = [[] for _ in range(200)]

That will create a list containing 200 different lists.




回答2:


You can multiply lists to achieve what you want to do:

big_list = [[]] * 200

Gives you a list of 200 empty lists. One caveat is that it will actually be 200 times the same list. This may not be what you want. For example appending to one of the lists will actually append to all, since they are all the same.

So for a list-of-lists, Paulo Bu's approach may be better. The multiplication feature is nice for constructing repeated strings or initializing a list of int's:

'A' * 5 -> 'AAAAA'
[0] * 3 -> [0, 0, 0]

The fact that the list contains different "names" for the same underlying object is not a problem here, it only becomes troublesome for mutable types, such as lists, dicts, sets, ... (but not the immutable tuples, for example)-



来源:https://stackoverflow.com/questions/22588389/python-initialize-a-list-of-lists-to-a-certain-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!