Initialize a list of objects in Python

前端 未结 4 1748
再見小時候
再見小時候 2021-02-04 03:49

I\'m a looking to initialize an array/list of objects that are not empty -- the class constructor generates data. In C++ and Java I would do something like this:



        
4条回答
  •  暖寄归人
    2021-02-04 04:00

    There isn't a way to implicitly call an Object() constructor for each element of an array like there is in C++ (recall that in Java, each element of a new array is initialised to null for reference types).

    I would say that your list comprehension method is the most Pythonic:

    lst = [Object() for i in range(100)]
    

    If you don't want to step on the lexical variable i, then a convention in Python is to use _ for a dummy variable whose value doesn't matter:

    lst = [Object() for _ in range(100)]
    

    For an equivalent of the similar construct in Java, you can of course use *:

    lst = [None] * 100
    

提交回复
热议问题