This article mainly introduces the use of defaultdict and lambda expressions in Python, which is shared here to everyone who needs to refer to the following
This example describes the use of defaultdict and lambda expressions in Python. Share to everyone for your reference, as follows:
As you can see from the tutorial, Defaultdict is a class that is used on a computer with Python2.7.6 that does not exist. The search in the document was not found, assuming that this might be Python 3.X proprietary. Because the tutorial is implemented based on Python 3.X. Later, a computer with Python 3.X still had a problem.
Turn to the network and discover that this class is actually a class in the collections module. It seems that learning is difficult to get rid of the network environment Ah!
This class is a subclass of Dict, overriding a method and adding an event variable. At the time of instantiation, the first parameter is provided to the initialization function of the default_factory. This parameter can be a type or a function, as for the type is not difficult to understand, in fact, the type is basically a factory function. However, sometimes we want to use this method to pass in a constant, this time we need to design a constant function alone or directly using a lambda expression.
Let's look at the following example:
>>> fromcollections Import defaultdict>>> C1 =defaultdict (int) >>>c1.get (123) >>> C1.get (' abc ') >>> Defconst (): Return 23>>> C2 =defaultdict (Const) >>>c2.get (123) >> > c2defaultdict (<functionconst at 0x000001d7e26f58c8>, {}) >>>c2[123]23>>>c2[' abc ']23 >>>c1[123]0
As can be seen from the above, this method can automatically give a default value for a key that does not exist for a Dictionary object. In this way, it is natural to implement value as a constant, but using lambda can make the code more concise:
>>> C3 =defaultdict (lambda:123) >>>c3[12]123
In recent usage scenarios, this approach has allowed the code to be much more concise, and the code readability of the custom has had no effect.