从特定键开始迭代排序的字典项

NI6

这个问题是在python 2.7中设置的。

OrderedDict用来存储一些项目,如下所示:

d = OrderedDict(zip(['a', 'b', 'c', 'd'], range(4)))

d等于{'a': 0, 'b': 1, 'c': 2, 'd': 3}

有没有一种方法可以d从特定键开始迭代dictionary 例如,我想d从键开始迭代项目'b'

提前谢谢了!

迈克·米勒

适用于Python 2和3的解决方案,使用itertools.dropwhile()

from __future__ import print_function

from collections import OrderedDict
from itertools import dropwhile

d = OrderedDict(zip(['a', 'b', 'c', 'd'], range(4)))

for k, v in dropwhile(lambda x: x[0] != 'b', d.items()):
    print(k, v)

输出:

b 1
c 2
d 3

Python 2,避免使用.items()::创建键值列表

for k, v in dropwhile(lambda x: x[0] != 'b', d.iteritems()):
    print(k, v)

定时

%timeit
for each in d.items()[d.keys().index('b'):]:
    pass
The slowest run took 5.18 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 3.27 µs per loop

%%timeit
for each in islice(d.iteritems(), d.keys().index('b'), None):
    pass
The slowest run took 5.23 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 3.05 µs per loop

%%timeit
for k, v in dropwhile(lambda x: x[0] != 'b', d.iteritems()):
    pass
The slowest run took 4.92 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 2.23 µs per loop

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章