Python标准库中collections对集合类型的数据结构进行了很多拓展操作,这些操作在我们使用集合的时候会带来很多的便利,多看看很有好处。
defaultdict是其中一个方法,就是给字典value元素添加默认类型,之前看到过但是没注意怎么使用,今天特地瞅了瞅。
首先是各大文章介绍的第一个例子:
代码如下:
import collections as coll
def default_factory():
return 'default value'
d = coll.defaultdict(default_factory, foo='bar')
print 'd:',d
print 'foo=>', d['foo']
print 'foo=>', d['bar'] #key为'bar'的元素不存在,会有一个默认值
输出结果是这样的:
代码如下:
d: defaultdict(
foo=> bar
foo=> default value
结论:这里可以看到,当我们取字典中一个没有的key的时候就会自动根据 default_factory生成一个value,类似于 d.get('bar','default value')
一个对比的例子:
如果一个字典中有个map的value是一个set,往这个set连续添加两个元素,使用原始的dict是这样的
代码如下:
dict_set1 = {}
#如果不知道这个字段中key有没有,需要先判断
if 'key' not in dict_set1:
dict_set1['key'] = set()
dict_set1['key'].add('111')
dict_set1['key'].add('000')
print dict_set1
如果使用defaultdict就是这样的
代码如下:
dict_set = coll.defaultdict(set)
dict_set['key'].add('000')
dict_set['key'].add('111')
print dict_set
好处就是不需要做set的初始化这个判断了。
两个使用的小案例
代码如下:
ss = '1111222233334444'
dict_int = coll.defaultdict(int)
for s in ss:
dict_int[s] += 1
print dict_int
'''''
官方文档的这个例子就能看到这种写法的简洁了
https://docs.python.org/2/library/collections.html#collections.defaultdict
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
... d[k].append(v)
...
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
'''
当我们做这种带有统计性质的数据操作时候,这个对象很好用。

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool