How to initialize a list to a certain value in Python

前端 未结 1 1618
南方客
南方客 2021-01-14 13:56

I\'d like to get a list where each item is set to a certain value (in my case, 0). I\'ve solved this in my code with the code below, but it feels so messy. Surely there\'s a

相关标签:
1条回答
  • 2021-01-14 14:35

    Multiply a one-element list by the desired length.

    maxWidths = [0] * maxCols
    

    In the above, all elements of the list will be the same objects. In case you're be creating a list of mutable values (such as dicts or lists), and you need them to be distinct, you can either use map as you did in the question, or write an equivalent list comprehension:

    [[] for dummy in range(100)]
    
    0 讨论(0)
提交回复
热议问题