Initialize a list of objects in Python

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

    I think the list comprehension is the simplest way, but, if you don't like it, it's obviously not the only way to obtain what you desire -- calling a given callable 100 times with no arguments to form the 100 items of a new list. For example, itertools can obviously do it:

    >>> import itertools as it
    >>> lst = list(it.starmap(Object, it.repeat((), 100)))
    

    or, if you're really a traditionalist, map and apply:

    >>> lst = map(apply, 100*[Object], 100*[()])
    

    Note that this is essentially the same (tiny, both conceptually and actually;-) amount of work it would take if, instead of needing to be called without arguments, Object needed to be called with one argument -- or, say, if Object was in fact a function rather than a type.

    From your surprise that it might take "as much as a list comprehension" to perform this task, you appear to think that every language should special-case the need to perform "calls to a type, without arguments" over other kinds of calls to over callables, but I fail to see what's so crucial and special about this very specific case, to warrant treating it differently from all others; and, as a consequence, I'm pretty happy, personally, that Python doesn't single this one case out for peculiar and weird treatment, but handles just as regularly and easily as any other similar use case!-)

提交回复
热议问题