【问题标题】:Keeping the same order for a dictionary保持字典的顺序相同
【发布时间】:2020-11-01 00:17:30
【问题描述】:

我需要编写一个名为 updateHand(hand, word) 的函数来执行此操作:

假设 'hand' 包含 word 中的所有字母。换句话说,这 假设无论字母出现在 'word' 中多少次,'hand' 都有 至少和那封信一样多。

更新手:用完给定单词中的字母并返回 新手,没有那些字母。

没有副作用:不修饰手。

word: string hand: dictionary (string -> int) 返回:dictionary (字符串 -> 整数)

我编写了代码,一切正常,除了返回“手”时,它的顺序不同:

updateHand({'u': 1, 'q': 1, 'a': 1, 'm': 1, 'l': 2, 'i': 1}, 'quail')

{'u': 0, 'i': 0, 'm': 1, 'a': 0, 'l': 1, 'q': 0}

谁能给我解决方案,甚至只是提示这个问题,因为我不明白......

【问题讨论】:

  • 您好,您是否尝试过使用保留插入顺序的collections.OrderedDict
  • 不,我对 python 并不陌生,抱歉 :)

标签: python dictionary python-3.5


【解决方案1】:

字典不会按插入顺序返回项目。

你需要的是OrderedDict:

from collections import OrderedDict

my_dict = OrderedDict()
my_dict['a'] = 1
...

这仅涉及

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-29
    • 1970-01-01
    • 1970-01-01
    • 2015-04-21
    • 2021-06-23
    • 2015-08-05
    • 2021-08-19
    • 2020-04-21
    相关资源
    最近更新 更多