加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 从特定键开始迭代有序的dict项

发布时间:2020-12-20 11:02:42 所属栏目:Python 来源:网络整理
导读:这个问题在 python 2.7中设计. 我正在使用OrderedDict存储一些项目,如下所示: d = OrderedDict(zip(['a','b','c','d'],range(4))) (d等于{‘a’:0,’b’:1,’c’:2,’d’:3}) 有没有办法从特定键开始迭代字典d? 例如,我想从键’b’开始迭代d项 提前谢
这个问题在 python 2.7中设计.

我正在使用OrderedDict存储一些项目,如下所示:

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

(d等于{‘a’:0,’b’:1,’c’:2,’d’:3})

有没有办法从特定键开始迭代字典d?
例如,我想从键’b’开始迭代d项

提前谢谢了!

解决方法

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

from __future__ import print_function

from collections import OrderedDict
from itertools import dropwhile

d = OrderedDict(zip(['a',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,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,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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读