繁体   English   中英

Python 3.0替代Python 2.0`.has_key`函数

[英]Python 3.0 replacement for Python 2.0 `.has_key` function

我的程序可以在Python 2.0中运行,但我需要在3.0或更高版本中运行。 问题在于新的Python不再具有.has_key函数。 我需要知道如何解决此问题,以便它可以在新版本中使用。

dictionary = {}

for word in words:
    if dictionary.has_key(word):
        dictionary[word]+=1
    else:
        dictionary[word]=1
bonus = {}
for key in sorted(dictionary.iterkeys()):
    print("%s: %s" % (key,dictionary[key]))
    if len(key)>5: #if word is longer than 5 characters (6 or greater) save to list, where we will get top 10 most common
        bonus[key]=dictionary[key]

in关键的测试:

if word in dictionary:

并将.iterkeys()替换为.keys() ; 在这种情况下,一个简单的sorted(dictionary)就足够了(在Python 2 3中)。

您的代码,使用最新技术进行了更紧凑的重写,将dictionary替换为collections.Counter()对象:

from collections import Counter

dictionary = Counter(words)

bonus = {}
for key in sorted(dictionary):
    print("{}: {}".format(key, dictionary[key]))
    if len(key) > 5:
        bonus[key] = dictionary[key]

尽管您也可以使用Counter.most_common()按频率(从高到低)顺序列出密钥。

如果要将代码从Python 2移植到3,则可能需要阅读Python移植指南

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM