我正在使用 Python 3.5.2,并且我有一个 dict
包含作为“键”的字符串元组,以及作为“值”的计数中的整数。我想做双重排序,其中第一优先级是键中的第一个字符串,第二优先级是整数值。请参阅下面的更深入的解释:
例如,我有一个字典:
>>> print(unorderedDict.items())
dict_items([(('has', 'accomplished'), 1), (('new', 'french'), 1), (('pieces', 'machinery'), 1), (('in', 'those'), 1), (('east', 'on'), 1), (('sectarian', 'principles'), 1), ((',', 'are'), 10), (('all', 'countries'), 2)......])
它包含两个字符串的元组作为键。 ('has', 'accomplished')
还有一个整数 ex 的值。 1
。前任。全部在一起:([(('all', 'countries'), 2)])
.
这本质上包含在文本中找到的所有唯一的单词组合,以元组形式作为键,以及单词的唯一组合在文本中出现的次数作为整数值。
我想要一种对 unorderedDict
进行排序的方法,第一个是键元组中的第一个字符串,第二个是值。
这样做的目的是让我有一个单词列表,加上最有可能跟随它的单词,以及列表中的下一个相同单词以及文本中下一个最可能跟随它的单词。
示例输出:
dict_items([(('all', 'the'), 10), (('all', 'of'), 7), (('big', 'drums), 12), (('big', 'dogs') 6)......])
请注意它如何首先按元组中的第一个字符串(按字母顺序)排序,然后按值(数字从高到低)排序。
为了执行这种类型的排序算法,我需要什么 Python 3 代码?
需要这种排序算法的主要原因是,我可以随机选择元组中的第一个字符串,并获取元组中更常见的第二个字符串(由 Count 中的整数标识)。
例如,我可以随机选择“all”,并发现它后面更有可能是“the”而不是“of”(“the”的 vount = 10,“of”的 vount = 7 )。
根据我自己的研究,我认为这与内置 dict
有关。排序方法和 lambda
也许是这样,但这对我来说是新领域,所以我真的不知道。
最佳答案
基本上这可以通过 OrderedDict
来完成:
from collections import OrderedDict
OrderedDict(sorted(unorderedDict.items(), key=lambda x: (x[0][0], x[1])))
# first string of key----^^^^^^^ ^^^^---value
但是我认为你应该考虑使用另一种数据结构。例如,list
的无序 dict
似乎是一个不错的选择,因为您只对第一个单词后面最常见的单词感兴趣:
import bisect
unorderedDict = dict([(('has', 'accomplished'), 1), (('has', 'done'), 5),
(('new', 'french'), 1), (('has', 'failed'), 3),
(('pieces', 'machinery'), 1), (('in', 'those'), 1),
(('east', 'on'), 1), (('sectarian', 'principles'), 1),
((',', 'are'), 10), (('all', 'countries'), 2)])
result = {}
for (key1, key2), counts in unorderedDict.items():
if key1 not in result:
# add a new key
result[key1] = [(counts, key2)]
else:
# We want the lists to be sorted so we can use bisection to do this quite efficient
bisect.insort_left(result[key1], (counts, key2))
>>> print(result)
{'sectarian': [(1, 'principles')],
'pieces': [(1, 'machinery')],
',': [(10, 'are')],
'all': [(2, 'countries')],
'has': [(1, 'accomplished'), (3, 'failed'), (5, 'done')], # sorted from low to high!
'new': [(1, 'french')],
'in': [(1, 'those')],
'east': [(1, 'on')]}
外部字典未排序,因为我怀疑它不需要(如果应该排序,那么我不知道如何排序)。
<小时/>替代方案可以是 collections.Counter
作为内部结构,因为它有一个很好的 .most_common
方法:
from collections import Counter
result = {}
for (key1, key2), counts in unorderedDict.items():
if key1 not in result:
result[key1] = Counter()
result[key1][key2] = counts
>>> result['has'].most_common() # returns it sorted!!!
[('done', 5), ('failed', 3), ('accomplished', 1)]
>>> result['has'].most_common(1)
[('done', 5)]
>>> result['has']['failed'] # can be accessed like a dictionary too
3
关于python - 对由字符串元组作为键和整数作为值组成的字典进行双重排序,首先按元组中的第一个字符串,然后按值整数Python 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41930086/