我正在尝试使用字典创建变量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]}
然而,这两个词典产生的结果并不相同(尽管它们产生的结果相似)
有人能告诉我哪里出了问题吗
非常感谢
从循环版本到理解的转换是机械的:将最里面的东西放在前面(适当修改-对于列表理解,我们只将参数带到^{,对于dict,我们从赋值中分离出适当的键和值),然后是所有
for
和if
子句,以原始顺序https://treyhunner.com/2015/12/python-list-comprehensions-now-in-color详细介绍了这如何用于列表理解;听写理解是类似的
我们也跳过了开头的
mfc_table_count = {}
,因为它对理解没有帮助-它将被忽略和替换(只要我们没有错误地引用它!)因此:
变成
相关问题 更多 >
编程相关推荐