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

后端 未结 2 1612
梦如初夏
梦如初夏 2021-01-25 11:53

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 contai

相关标签:
2条回答
  • 2021-01-25 12:16

    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)-

    0 讨论(0)
  • 2021-01-25 12:17

    You can use list comprehension for example:

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

    That will create a list containing 200 different lists.

    0 讨论(0)
提交回复
热议问题