以下是我的代码:
import heapq
sentences_scores = {'Fruit': 6, 'Apple': 5, 'Vegetables': 3, 'Cabbage': 9, 'Banana': 1}
summary = heapq.nlargest(3, sentences_scores, key = sentences_scores.get)
text = ""
for sentence in summary:
text = text + sentence + ' '
print(text)
我得到输出:
Cabbage Fruit Apple
但我想得到输出:
Fruit Apple Cabbage
我该怎么做呢? 问题来源StackOverflow 地址:/questions/59386998/python-order-of-output-from-a-set
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
首先,你的字典是无序的,所以你不能得到相同的顺序;该命令实际上并不存在。正如注释所说,使用OrderedDict来代替。 另外,如果你要处理水果,不要给可变句命名。:P
import heapq
from collections import OrderedDict
fruit_scores = OrderedDict([('Fruit', 6), ('Apple', 5), ('Vegetables', 3), ('Cabbage', 9), ('Banana', 1)])
best_fruit = heapq.nlargest(3, sentences_scores, key = sentences_scores.get)
best_fruit_scores = OrderedDict((fruit, score)
for fruit, score in fruit_scores.items() if fruit in best_fruit)
# => OrderedDict([('Fruit', 6), ('Apple', 5), ('Cabbage', 9)])
best_fruit_names = [fruit
for fruit in fruit_scores if fruit in best_fruit]
# => ['Fruit', 'Apple', 'Cabbage']