Creating defaultdict with an empty numpy array

I'm wondering if there is a smarter way to create defaulted defaults from collections. The default value for the dict parameter must be an empty ndarray value.

My best result so far:

import collections d = collections.defaultdict(lambda: numpy.ndarray(0)) 

However, I am wondering if it is possible to skip the lambda term and create a dict in a more direct manner. For instance:

 d = collections.defaultdict(numpy.ndarray(0)) # <- Nice and short - but not callable 
+6
source share
1 answer

You can use functools.partial() instead of lambda:

 from collections import defaultdict from functools import partial defaultdict(partial(numpy.ndarray, 0)) 

You always need to call defaultdict() , and numpy.ndarray() always requires at least one argument, so you cannot just pass numpy.ndarray here.

+11
source

Source: https://habr.com/ru/post/973028/


All Articles