简体   繁体   English

遍历有序字典中的最后x个元素?

[英]Going through the last x elements in an ordered dictionary?

I want to go through an x number of the most recently added entries of an ordered dictionary. 我想查看一个有序词典中x个最新添加的条目。 So far, the only way I can think of is this: 到目前为止,我能想到的唯一方法是:

listLastKeys = orderedDict.keys()[-x:]
for key in listLastKeys:
    #do stuff with orderedDict[key]

But it feels redundant and somewhat wasteful to make another list and go through the ordered dictionary with that list when the ordered dictionary should already know what order it is in. Is there an alternative way? 但是,当有序字典应该已经知道它的顺序时,制作另一个列表并通过该列表浏览有序字典会感到多余并且有些浪费。是否有另一种方法? Thanks! 谢谢!

Iterate over the dict in reverse and apply an itertools.islice : 反向迭代字典并应用itertools.islice

from itertools import islice

for key in islice(reversed(your_ordered_dict), 5):
    # do something with last 5 keys

Instead of reversing it like you are, you can loop through it in reverse order using reversed() . 与其像您那样反转它,还可以使用reversed()以相反的顺序遍历它。 Example: 例:

D = {0 : 'h', 1: 'i', 2:'j'}

x = 1
for key in reversed(D.keys()):
    if x == key:
        break

You could keep a list of the keys present in the dictionary last run. 您可以保留上次运行字典中存在的键的列表。

I don't know the exact semantics of your program, but this is a function that will check for new keys. 我不知道您的程序的确切语义,但这是一个将检查新键的函数。

keys=[] #this list should be global

def checkNewKeys(myDict):
    for key, item in myDict.iteritems():
        if key not in keys:
            #do what you want with new keys
            keys.append(key)

This basically keep track of what was in the dictionary the whole run of your program, without needing to create a new list every time. 这基本上可以跟踪程序整个运行过程中词典中的内容,而无需每次都创建一个新列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM