Initialize a list of objects in Python

前端 未结 4 1808
再見小時候
再見小時候 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:04

    You should note that Python's equvalent for Java code (creating array of 100 null references to Object):

    Object arr = new Object[100];
    

    or C++ code:

    Object **arr = new Object*[100];
    

    is:

    arr = [None]*100
    

    not:

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

    The second would be the same as Java's:

    Object arr = new Object[100];
    for (int i = 0; i < arr.lenght; i++) {
        arr[i] = new Object();
    }
    

    In fact Python's capabilities to initialize complex data structures are far better then Java's.


    Note: C++ code:

    Object *arr = new Object[100];
    

    would have to do as much work as Python's list comprehension:

    • allocate continuous memory for 100 Objects

    • call Object::Object() for each of this Objects

    And the result would be a completely different data structure.

提交回复
热议问题