python 字典的问题
来源:互联网 发布:加权余量法 知乎 编辑:程序博客网 时间:2024/06/16 09:21
#Part I
keys=list(counts.keys()) for key in keys: if key in thewords: counts.pop(key)
要遍历字典过程中,如果没有
keys=list(counts.keys()) #对keys转换成list,不再是dict_key.
对字典的处理过程中删除增加会报错:RuntimeError: dictionary changed size during iteration
#del counts[key]也可以换成counts.pop(key)
#Part II
上述写法可以更为精简,参考: Python if 和 for 的多种写法
#源代码是Mooc的python课程 的6.9的作业,
#上面切词的方式是用空格替换掉所有非字母数字字符,此代码用正则表达式来切词
import rere_word=re.compile(r'[a-z]+')def get_words():#切词 txt_path = "hamlet.txt" with open(txt_path,"r") as txt: txt_r=txt.read() txt=txt_r.lower() word_list=re_word.findall(txt) print('word:%s'%word_list) return word_list#对每个单词出现的次数统计def count_words(object): counts={} for word in object:#也可以写成counts[word]=counts.get(word,0) if word in counts: counts[word]=counts[word]+1 else: counts[word]=1 thewords=['the', 'a', 'to', 'of', 'a', 'i', 'in', 'and', 'you', 'your','it','that','is'] keys=list(counts.keys()) # for key in keys: # if key in thewords: # counts.pop(key) [counts.pop(key) for key in keys if key in thewords]#等价comment的部分 items=list(counts.items()) items.sort(key=lambda x:x[1],reverse=True) print(items) for i in range(10): word,count=items[i] print("{0:<10}{1:>5}".format(word,count))if __name__ == '__main__': words=get_words() count_words(words)此上的代码可以用来做Github 上的0006题
阅读全文
0 0
- python 字典的问题
- python 字典排序问题
- <Python>字典,可爱的字典
- python 合并字典效率问题
- python字典value为列表时遇到的问题
- Python中字典的浅拷贝和深拷贝问题
- python解决字典中的值是列表问题的方法
- Python字典key值查询效率低的问题
- python中在list中添加字典遇到的问题
- python 字典和列表的读取速度问题
- Python——列表中存放字典遇到的问题
- python解决字典中的值是列表问题的方法
- python一道关于颠倒字典中键值的问题
- python 字典中的copy函数的浅拷贝问题
- python中在list中添加字典遇到的问题
- 如果实现python字典的只读, 考虑字典内容有list, dict的嵌套问题
- Python的字典操作
- Python的字典
- spring+springMVC+mybatis框架 兼容mongodb(mysql+mongodb)
- CC2541/CC2530 pwm
- Havel-Hakimi定理(判断一个度序列是否可图)
- Git回滚到历史节点(SourceTree篇)
- VS2015静态库与动态库的使用
- python 字典的问题
- 网页前端代码存档
- 服务器安装之--nmon
- 序列化和反序列化Serializable-2
- Android开发能用上的技术
- BZOJ 1385: [Baltic2000]Division expression
- Tyvj4876:骰子游戏 ((FFT/NTT)+倍增+DP)
- Gradle配置记录
- 协议