【问题标题】:dict.get or list check, which is faster?dict.get 或 list check,哪个更快?
【发布时间】:2022-11-20 00:47:37
【问题描述】:

如果我想获得一个带有 ID 的机器人,它在以下两者之间更快:

storage = {
    'bots': [
        { 'id': 123, 'auth': '81792367' },
        { 'id': 345, 'auth': '86908472' },
        { 'id': 543, 'auth': '12343321' }
    ]
}

id = 345
bot = next(bot['auth'] for bot in storage['bots'] if bot['id'] == id)

storage = {
    'bots': {
        123: '81792367',
        345: '86908472',
        543: '12343321',
    }
}

id = 345
bot = storage['bots'][id]

哪些必须用于 Python pep8 或最漂亮?

【问题讨论】:

  • 如果您想知道在您的特定情况下什么更快,那么试试看.如果您有关于风格的问题,那是题外话。
  • 使用 timeit 模块或 iPython 魔术函数 %timeit 做一些研究。

标签: python pep8


【解决方案1】:

请记住,查找列表的时间复杂度(即使用 in 关键字)是 O(n),而对于字典 (Time Complexity of Collection Ops),同一操作的时间复杂度为 O(1)

同时,两者获取项目的时间复杂度相同 (O(1))。所以,我会说你最好使用第二种方法。

【讨论】:

    猜你喜欢
    • 2018-08-15
    • 1970-01-01
    • 2011-03-13
    • 2020-10-08
    • 1970-01-01
    • 1970-01-01
    • 2010-11-10
    • 2012-10-03
    • 2011-02-15
    相关资源
    最近更新 更多