【问题标题】:What will be the time complexity of list(dict.keys()) in python3python3中list(dict.keys())的时间复杂度是多少
【发布时间】:2022-08-17 00:15:46
【问题描述】:

我正在使用 list(dict.keys()) 解决算法问题,这需要更多时间 比 OrderedDict dict.popitem(0) 我知道它会返回生成器类型对象,我们可以遍历它并获取列表中的每个元素,如范围。

    标签: python-3.x dictionary


    【解决方案1】:

    当您创建一个由所有元素组成的新列表时,时间复杂度为O(n)

    如果你只想要第一个,我建议你next(iter(dict)),它将在O(1) 为你带来第一把钥匙。

    您可以捕获StopIteration 以确保字典不为空或从next() 返回默认值:

    >>> def take_first(d):
    ...   return next(iter(d), None)
    ...
    >>> take_first({"a": 1, "b": 2})
    'a'
    >>> take_first({})
    >>> # (None)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-24
      • 2014-05-27
      • 1970-01-01
      • 1970-01-01
      • 2012-02-13
      相关资源
      最近更新 更多