Home  >  Article  >  Backend Development  >  Usage of defaultdict and lambda expressions in Python

Usage of defaultdict and lambda expressions in Python

不言
不言Original
2018-04-09 14:50:233018browse

This article mainly introduces the usage of defaultdict and lambda expressions in Python. I will share it with you here. Friends who need it can refer to it

The examples in this article describe the usage of defaultdict and lambda expressions in Python. Share it with everyone for your reference, the details are as follows:

From the tutorial, I saw that defaultdict is a class, but when I use it on a computer with Python 2.7.6, I find that it does not exist. I searched the documentation and couldn't find it, so I took it for granted that this might be exclusive to Python 3.X. Because the tutorial is based on Python 3.X. Later, I changed to a computer with Python 3.X and still had the problem.

I turned to the Internet and found that this class is actually a class in the collections module. It seems that it is difficult to get rid of the online environment for learning!

This class is a subclass of dict, which overrides a method and adds an event variable. At the time of instantiation, the first parameter is provided to the initialization function of default_factory. This parameter can be a type or a function. As for the type, it is not difficult to understand. In fact, types are basically factory functions. However, sometimes we want to use this method to pass in a constant. In this case, we need to design a constant function separately or use lambda expressions directly.

Let’s first look at the following demonstration:

>>> fromcollections import defaultdict
>>> c1 =defaultdict(int)
>>>c1.get(123)
>>>c1.get('abc')
>>> defConst():
return 23
>>> c2 =defaultdict(Const)
>>>c2.get(123)
>>> c2
defaultdict(<functionConst at 0x000001D7E26F58C8>, {})
>>>c2[123]
23
>>>c2[&#39;abc&#39;]
23
>>>c1[123]
0

As can be seen from the above, this method can automatically set the key for a dictionary object that does not exist. Give a default value. Using the above method, you can naturally realize that the value is a constant, but using lambda can make the code more concise:

>>> c3 =defaultdict(lambda :123)
>>>c3[12]
123

In the recent encounter In usage scenarios, this method can make the code much simpler, and it has no impact on the readability of the code after getting used to it.

Related recommendations:

A simple introductory guide to the defaultdict module and namedtuple module in Python


The above is the detailed content of Usage of defaultdict and lambda expressions in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn