这两种不同的词典结构有什么区别?

2024-04-25 00:25:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用字典创建变量mfc_table_count。我使用for循环创建了字典,如下所示:

mfc_table_count = {}
for tag in word_counts:
    for word in word_counts[tag]:
        if word not in mfc_table or word_counts[tag][word] > mfc_table_count[word]:  # initialise word key or replace word key with higher count
            mfc_table_count[word] = word_counts[tag][word]

然后,我根据上述内容创建了词典理解:

mfc_table_count = {}
mfc_table_count = {word:(word_counts[tag][word]
                          if word not in mfc_table_count
                          or word_counts[tag][word] > mfc_table_count[word] 
                          else mfc_table_count[word]) 
                    for tag in word_counts for word in word_counts[tag]}

然而,这两个词典产生的结果并不相同(尽管它们产生的结果相似)

有人能告诉我哪里出了问题吗

非常感谢


1条回答
网友
1楼 · 发布于 2024-04-25 00:25:46

从循环版本到理解的转换是机械的:将最里面的东西放在前面(适当修改-对于列表理解,我们只将参数带到^{,对于dict,我们从赋值中分离出适当的键和值),然后是所有forif子句,以原始顺序

https://treyhunner.com/2015/12/python-list-comprehensions-now-in-color详细介绍了这如何用于列表理解;听写理解是类似的

我们也跳过了开头的mfc_table_count = {},因为它对理解没有帮助-它将被忽略和替换(只要我们没有错误地引用它!)

因此:

mfc_table_count = {} # redundant
for tag in word_counts: # 1
    for word in word_counts[tag]: # 2
        if word not in mfc_table or word_counts[tag][word] > mfc_table_count[word]: # 3
            mfc_table_count[word] = word_counts[tag][word] # 0

变成

mfc_table_count = {
    word: word_counts[tag][word] # 0
    for tag in word_counts # 1
    for word in word_counts[tag] # 2
    if word not in mfc_table or word_counts[tag][word] > mfc_table_count[word] # 3
}

相关问题 更多 >