栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python字典的get()方法介绍

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python字典的get()方法介绍

1 背景

Python字典的get()方法介绍
今天看到一个字典用法,自己学习一下。

2 字典常用初始化

下面这个方式,应该是最常见的吧。

dictOne = {"one":1,"two":1}
myList = ["three", "four"]
for i in Mylist:
	if i in dictOne:
	    dictOne[i] + =1
	else:
		dictOne[i] =1
3 get()方法介绍

有幸看到了下面这个用法(最后一行)

import jieba # jieba中文分词库

with open('test.txt', 'r', encoding='UTF-8') as novelFile:
    novel = novelFile.read()
# print(novel)
stopwords = [line.strip() for line in open('stop.txt', 'r', encoding='UTF-8').readlines()]
novelList = list(jieba.lcut(novel))
novelDict = {}

# 统计出词频字典
for word in novelList:
    if word not in stopwords:
            # 不统计字数为一的词
            if len(word) == 1:
                continue
            else:
                novelDict[word] = novelDict.get(word, 0) + 1

novelDict[word] = novelDict.get(word, 0) + 1
这行代码就等于我们开始定义的那个常用用法。
如果novelDict这个字典里面存在,就加1,不然就设置一个默认值0给这个key

下面在来一个例子:

dict_data ={1:'one',2:'two',3:'three',4:'four'}
 

print(dict_data.get(1))
print(dict_data.get(2))
print(dict_data.get(5))
print(dict_data.get(5,'notfound'))

运行结果

one
two
None
not found
4 总结:
dict.get(key, 0) + 1

这个操作好自然,舒服!!!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/938381.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号