【发布时间】:2012-03-14 00:02:13
【问题描述】:
我需要帮助找到从频率字典中构建频率排序列表的快捷方式。我可以通过将每个元素附加到列表然后将每个列表附加到“列表列表”(只有频率 1-3 很容易)来构建列表列表(见下文),但是如果我有频率上升会发生什么到100个或更多?!必须有更好的方法。
dictionary = {'ab':2, 'bc':3, 'cd':1, 'de':1, 'ef':3, 'fg':1, 'gh':2}
list_1 = []
list_2 = []
list_3 = []
list_of_lists = []
for key, value in dictionary.items():
if value == 1:
list_1.append(key)
for key, value in dictionary.items():
if value == 2:
list_2.append(key)
for key, value in dictionary.items():
if value == 3:
list_3.append(key)
list_of_lists.append(list_1)
list_of_lists.append(list_2)
list_of_lists.append(list_3)
print list_of_lists
在 Python 中运行的副本如下所示:
[['de', 'cd', 'fg'], ['ab', 'gh'], ['ef', 'bc']]
这正是我想要的,但它不适用于频率为 100+ 的 100,000+ 个单词的语料库。请帮助我找到一种更好、更简单的方式来构建我的列表。
【问题讨论】: