Python 检查列表中是否存在字典键?

Python 检查列表中是否存在字典键?,python,python-3.x,Python,Python 3.x,因此,我是Python的中级初学者,我想知道我在这段代码中是否走上了正确的轨道。在学校里,我被分配了一项文件压缩任务,在这项任务中,我们必须制定自己的算法来压缩文本文件。对于这段代码的最后部分,我需要遍历列表并检查其中是否存在dict键,如果为True,则将列表项转换为dict的值。有人能告诉我我是否在正确的轨道上吗 commonwords = {'the' : '@', 'of' : '$', 'to' : '%','and' : '^', 'you' : '&', 'becaus

因此,我是Python的中级初学者,我想知道我在这段代码中是否走上了正确的轨道。在学校里,我被分配了一项文件压缩任务,在这项任务中,我们必须制定自己的算法来压缩文本文件。对于这段代码的最后部分,我需要遍历列表并检查其中是否存在dict键,如果为True,则将列表项转换为dict的值。有人能告诉我我是否在正确的轨道上吗

commonwords =  {'the' : '@', 'of' : '$', 'to' : '%','and' : '^', 'you' : 
'&', 'because' : '#', 'in' : '*', 'it' : '(', 'is' : ')', 'they' : '=',
            'are' : '+', 'this' : '!','but' : ',', 'have' : '.', 'by' : '/'}

def compress(file):
    file_obj = open(file,"r")
    file_contents = file_obj.read().split()
    for word in file_contents:
        if commonwords.keys() in file_contents:
            file_contents[i] == commonwords[i]
    return file_contents

不完全正确。您似乎在文件中遍历单词,但从不检查单词是否是字典键<代码中的code>i最初未初始化,将导致未定义的错误,请注意,对于赋值,使用赋值运算符
=
,而不是相等运算符

我建议使用此代码,这将解决您的问题:

commonwords =  {'the' : '@', 'of' : '$', 'to' : '%','and' : '^', 'you' :  '&', 'because' : '#', 'in' : '*', 'it' : '(', 'is' : ')', 'they' : '=', 'are' : '+', 'this' : '!','but' : ',', 'have' : '.', 'by' : '/'}

def compress(file):
    file_obj = open(file,"r")
    file_contents = file_obj.read().split()
    for x, word in enumerate(file_contents):
        if word in commonwords:
            file_contents[x] = commonwords[word]
    file_obj.close()
    return file_contents

注意此处使用的
enumerate
。它可以帮助您在遍历列表元素时跟踪索引。

如果我没弄错,您想检查文件内容中的任何单词是否是commonwords中的关键字吗

你可以这么做

for word in file_contents:
    if word in commonwords:
        word.replace(word, commonwords[word])

Python理解,如果您键入“in file_contents”,则表示键。

关闭,但不关闭。。。您要检查的是文件的
word
是否在
commonwords
中,而不是
commonword.keys()
列表是否包含在
文件内容中(逐字):

def compress(file):
    with open(file,"r") as f:
        words = f.read().split()

    for i, word in enumerate(words):
       if word in commonwords: 
            words[i] = commonwords[word]

    return words

您没有使用迭代器变量,
word
。那是故意的吗?
中的
文件内容是否为
word
。Python有一个正确处理文件的方法。查看如何将
关键字一起使用,在这里它将为您提供:
与open(file,'r')作为file\u obj:
。为什么要使简单的高度优化的O(1)查找成为低效的O(N)顺序查找?删除
keys=commonwords.keys()
行,只需使用
if-word-in-commonwords
@brunodesshuilliers谢谢。那是匆忙编码的。