【问题标题】:How do you get the first 3 elements in Python OrderedDict?如何获得 Python OrderedDict 中的前 3 个元素?
【发布时间】:2015-07-26 20:37:34
【问题描述】:

如何获得 Python OrderedDict 中的前 3 个元素?

也可以从这个字典中删除数据。

例如:如何获取 Python OrderedDict 中的前 3 个元素并删除其余元素?

【问题讨论】:

    标签: python dictionary ordereddictionary


    【解决方案1】:

    让我们创建一个简单的OrderedDict

    >>> from collections import OrderedDict
    >>> od = OrderedDict(enumerate("abcdefg"))
    >>> od
    OrderedDict([(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g')])
    

    分别返回前三个

    >>> list(od)[:3]
    [0, 1, 2]
    >>> list(od.values())[:3]
    ['a', 'b', 'c']
    >>> list(od.items())[:3]
    [(0, 'a'), (1, 'b'), (2, 'c')]
    

    删除除前三项之外的所有内容:

    >>> while len(od) > 3:
    ...     od.popitem()
    ... 
    (6, 'g')
    (5, 'f')
    (4, 'e')
    (3, 'd')
    >>> od
    OrderedDict([(0, 'a'), (1, 'b'), (2, 'c')])
    

    【讨论】:

    • .items().values() 返回列表(至少在 Python 2.7 中),因此无需使用 list()。 Python 3 有什么不同吗?
    • @John Yes。我选择不通过提到在 2.x 中返回列表来使答案复杂化:这里没有实际影响,无论如何,现在每个人都应该考虑到 3.x 编写(即使他们的代码还没有瞄准它)。
    • 值得注意的是,OrderedDict(list(od.items())[:3]) 将返回一个字典,其中仅包含单行中的前三个项目。
    【解决方案2】:

    您可以使用这种迭代方法来完成工作。

    x = 0
    for i in ordered_dict:
        if x > 3:
            del ordered_dict[i]
        x += 1
    

    首先,您只需创建一个计数器变量x,并将其赋值为 0。然后循环遍历ordered_dict 中的键。通过看到x 大于 3,您可以看到检查了多少项目,这是您想要的值的数量。如果已经检查了 3 个项目,则您 delete 来自 ordered_dict 的那个项目。


    这是一种更清洁的替代方法(感谢 cmets)

    for i, k in enumerate(ordered_dict):
        if i > 2:
            del ordered_dict[k]
    

    这通过使用 enumerate 为每个键分配一个数字来工作。然后它检查该数字是否小于二(0、1 或 2)。如果数字不是 0、1 或 2(这将是前三个元素),则字典中的该项将被删除。

    【讨论】:

    • 啊,我明白你的意思了。我的错。你可以在这里使用enumerate
    • Nvm,但是,枚举更好。
    • 类似这样的东西:for i, k in enumerate(odct): if i > 2: del odct[k] 显然,不是一行,因为这是一个语法错误:p
    • 请注意,此解决方案对于带有 n RuntimeError 的 python3 失败,因为在迭代期间不允许更改字典的大小
    【解决方案3】:

    它与其他字典没有什么不同:

    d = OrderedDict({ x: x for x in range(10) })
    
    i = d.iteritems()
    a = next(i)
    b = next(i)
    c = next(i)
    
    d = OrderedDict([a,b,c])
    # or
    d.clear()
    d.update([a,b,c])
    

    【讨论】:

      猜你喜欢
      • 2023-03-24
      • 2017-09-01
      • 2021-03-16
      • 2020-04-22
      • 1970-01-01
      • 2021-06-11
      • 2014-05-01
      • 2016-02-18
      • 2019-10-30
      相关资源
      最近更新 更多