开发者社区 问答 正文

Python:集合输出的顺序

以下是我的代码:

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

展开
收起
kun坤 2019-12-25 21:45:36 912 分享 版权
1 条回答
写回答
取消 提交回答
  • 首先,你的字典是无序的,所以你不能得到相同的顺序;该命令实际上并不存在。正如注释所说,使用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']
    
    2019-12-25 21:45:42
    赞同 展开评论
问答分类:
问答地址: