首页 > 编程语言 > 详细

python - dict.setdefault

时间:2017-04-15 00:29:54      阅读:338      评论:0      收藏:0      [点我收藏+]
index = dict.serdefault(key,default)

尝试往dict中插入新键值key,如果key已存在就原dict不变,否则插入key:defalut;返回值为key在dict中的下标

可以用来实现稀疏矩阵https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html

>>> docs = [["hello", "world", "hello"], ["goodbye", "cruel", "world"]]
>>> indptr = [0]
>>> indices = []
>>> data = []
>>> vocabulary = {}
>>> for d in docs:
...     for term in d:
...         index = vocabulary.setdefault(term, len(vocabulary))
...         indices.append(index)
...         data.append(1)
...     indptr.append(len(indices))
...
>>> csr_matrix((data, indices, indptr), dtype=int).toarray()
array([[2, 1, 0, 0],
       [0, 1, 1, 1]])

 

python - dict.setdefault

原文:http://www.cnblogs.com/liziran/p/6711229.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!