【发布时间】:2016-12-04 15:09:36
【问题描述】:
我有一本字典ngram_list如下:
ngram_list = dict_items([
('back to back breeding', {'wordcount': 4, 'count': 3}),
('back breeding', {'wordcount': 2, 'count': 5}),
('several consecutive heats', {'wordcount': 3, 'count': 2}),
('how often should', {'wordcount': 3, 'count': 2}),
('often when breeding', {'wordcount': 3, 'count': 1})
])
我想将列表从最短字数排序到最大,然后遍历字典,如果键是任何其他项的子字符串,则将其删除(子字符串项)。
预期输出:
ngram_list = dict_items([
('several consecutive heats', {'wordcount': 3, 'count': 2}),
('how often should', {'wordcount': 3, 'count': 2}),
('often when breeding', {'wordcount': 3, 'count': 1}),
('back to back breeding', {'wordcount': 4, 'count': 3})
])
【问题讨论】:
-
你的最终预期输出字典是什么?
-
@Skycc 更新抱歉
-
所以你希望你的输出作为字典或像 dict.items() 这样的元组列表返回?您将需要
OrderedDict用于按顺序排序的项目 -
您是否也想替换一个键是另一个键的子字符串,但是是不同的词?就像“猫”和“灾难”一样?
-
@tobias_k 只有完整的单词/ngrams/表达式,而不是单词的一部分
标签: python python-2.7 python-3.x dictionary