当前位置:首页 > 后端开发 > Python collections.defaultdict() 与 dict的使用和区别

Python collections.defaultdict() 与 dict的使用和区别

7个月前 (05-20)45

看样子这个文档是难以看懂了。直接看示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import  collections
=  [( 'yellow' 1 ), ( 'blue' 2 ), ( 'yellow' 3 ), ( 'blue' 4 ), ( 'red' 1 )]
# defaultdict
=  collections.defaultdict( list )
for  k, v  in  s:
     d[k].append(v)
# Use dict and setdefault   
=  {}
for  k, v  in  s:
     g.setdefault(k, []).append(v)
      
# Use dict
=  {}
for  k, v  in  s:
     e[k]  =  v
##list(d.items())
##list(g.items())
##list(e.items())

 

看看结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
list (d.items())
[( 'blue' , [ 2 4 ]), ( 'red' , [ 1 ]), ( 'yellow' , [ 1 3 ])]
>>>  list (g.items())
[( 'blue' , [ 2 4 ]), ( 'red' , [ 1 ]), ( 'yellow' , [ 1 3 ])]
>>>  list (e.items())
[( 'blue' 4 ), ( 'red' 1 ), ( 'yellow' 3 )]
>>> d
defaultdict(< class  'list' >, { 'blue' : [ 2 4 ],  'red' : [ 1 ],  'yellow' : [ 1 3 ]})
>>> g
{ 'blue' : [ 2 4 ],  'red' : [ 1 ],  'yellow' : [ 1 3 ]}
>>> e
{ 'blue' 4 'red' 1 'yellow' 3 }
>>> d.items()
dict_items([( 'blue' , [ 2 4 ]), ( 'red' , [ 1 ]), ( 'yellow' , [ 1 3 ])])
>>> d[ "blue" ]
[ 2 4 ]
>>> d.keys()
dict_keys([ 'blue' 'red' 'yellow' ])
>>> d.default_factory
< class  'list' >
>>> d.values()
dict_values([[ 2 4 ], [ 1 ], [ 1 3 ]])

 

可以看出

collections.defaultdict(list)使用起来效果和运用dict.setdefault()比较相似

python help上也这么说了

When each key is encountered for the first time, it is not already in the mapping; so an entry is automatically created using the default_factory function which returns an empty list. The list.append() operation then attaches the value to the new list. When keys are encountered again, the look-up proceeds normally (returning the list for that key) and the list.append() operation adds another value to the list. This technique is simpler and faster than an equivalent technique using dict.setdefault():

 

说这种方法会和dict.setdefault()等价,但是要更快。

有必要看看dict.setdefault()

setdefault(key[, default])

If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.

如果这个key已经在dictionary里面存着,返回value.如果key不存在,插入key和一个default value,返回Default. 默认的defaults是None.

 

但是这里要注意的是defaultdict是和dict.setdefault等价,和下面那个直接赋值是有区别的。从结果里面就可以看到,直接赋值会覆盖。

 

从最后的d.values还有d[“blue”]来看,后面的使用其实是和dict的用法一样的,唯一不同的就是初始化的问题。defaultdict可以利用工厂函数,给初始keyi带来一个默认值。

这个默认值也许是空的list[]  defaultdict(list), 也许是0, defaultdict(int).

 

再看看下面的这个例子。

defaultdict(int) 这里的d其实是生成了一个默认为0的带key的数据字典。你可以想象成 d[key] = int default (int工厂函数的默认值为0)

 

d[k]所以可以直接读取 d[“m”] += 1 就是d[“m”] 就是默认值 0+1 = 1

后面的道理就一样了。

1
2
3
4
5
6
7
>>> s  =  'mississippi'
>>> d  =  defaultdict( int )
>>>  for  in  s:
...     d[k]  + =  1
...
>>>  list (d.items())
[( 'i' 4 ), ( 'p' 2 ), ( 's' 4 ), ( 'm' 1 )]

来源链接:https://www.cnblogs.com/skying555/p/5222697.html

标签: Collections

“Python collections.defaultdict() 与 dict的使用和区别” 的相关文章

java中排序函数sort()使用,Arrays.sort()和Collections.sort()

java中排序函数sort()使用,Arrays.sort()和Collections.sort()

Java中常用的数组或集合排序的方法有两个,一个是java.util.Arrays中的静态方法Arrays.sort(),还有一个是java.util.Collections中的静态方法...

python 之SET和collections

一.set集合set是一个无序且不重复的元素集合,基本功能包括关系测试和消除重复元素. 集合对象还支持union(联合), intersection(交), difference(差)、...

python中的collections

        python中有大量的内置模块,很多是属于特定开发的功能性模块,但collections是属于对基础数据的类型的补充模块,因...

Java之Collections.emptyList()、emptySet()、emptyMap()的作用和好处以及要注意的地方

Java之Collections.emptyList()、emptySet()、emptyMap()的作用和好处以及要注意的地方

先说明一下好处有哪些:1,如果你想 new 一个空的 List ,而这个 List 以后也不会再添加元素,那么就用 Collections.emptyList() 好了。new Arra...

Collections.synchronizedList线程安全性陷阱

摘要: 详细的解析:Collections.synchronizedList 1 :关注要点,为什么在有synchroniezed方法的同时会出现 Collections.syn...

Java中Arrays、Collections的Sort方法

Collections类提供了两个sort方法,目标都是List<T> list,不同时可选择自己指定一个Comparator。 public s...

java中的排序(自定义数据排序)--使用Collections的sort方法

java中的排序(自定义数据排序)--使用Collections的sort方法

排序:将一组数据按相应的规则 排列 顺序 1.规则:       基本数据类型:日常的大小排序。...

Collections.unmodifiableList()的使用与场景

在《重构——改善既有代码的设计》一书中,有一种重构手法叫Encapsulate Collection(封装集群),为了演示该重构手法,我写了四个类,通过对比重构前后的代码,加深...

Guava源码分析——Immutable Collections(4)

Guava源码分析——Immutable Collections(4)

Immutable的集合体系,还有中很重要的集合没有介绍,就是ImmutableMap,通过UML图,可以看出ImmutableMap的结构体系。 首先来看一下Immuta...

C#(07):并发集合 System.Collections.Concurrent 命名空间

 一、概述: System.Collections.Concurrent 命名空间提供多个线程安全集合类。 当有多个线程并发访问集合时,应使用这些类代替 System.Co...