提问人:NI6 提问时间:3/9/2018 最后编辑:jppNI6 更新时间:3/12/2018 访问量:1036
从特定键开始迭代有序的字典项
Iterating ordered dict items starting from specific key
问:
该问题的样式在 python 2.7 中。
我用来存储一些项目,如下所示:OrderedDict
d = OrderedDict(zip(['a', 'b', 'c', 'd'], range(4)))
(d
等于{'a': 0, 'b': 1, 'c': 2, 'd': 3}
)
有没有办法迭代字典,从特定的键开始?
例如,我想从键开始迭代项目d
d
'b'
提前非常感谢!
答:
-1赞
omu_negru
3/9/2018
#1
这行得通吗?
for x in list(a.keys())[a.index(my_key):]:
print(a[x])
要从何处开始的密钥在哪里my_key
2赞
MooingRawr
3/9/2018
#2
您可以通过查找 by use 的值并切掉您需要的位置来进行迭代。如果您有自己的方式知道要从哪里开始,请替换。b
items()
d.keys().index('b')
from collections import OrderedDict
d = OrderedDict(zip(['a', 'b', 'c', 'd'], range(4)))
for each in d.items()[d.keys().index('b'):]:
print(each)
使用允许您像往常一样关闭键和值。items()
评论
0赞
MooingRawr
3/9/2018
我知道,你知道我回答 Python 2 问题感觉不对,但是呃。由于 opThe question is styled in python 2.7 .
0赞
cs95
3/9/2018
啊,没看到。继续;D
0赞
jpp
3/9/2018
如果我错了,请纠正我,但这不是复制了整个字典吗?更好用?iteritems()
0赞
MooingRawr
3/9/2018
@jpp不起作用,因为生成器没有不允许切片的调用,而这正是 OP 想要的。因此,Coldspeed 的原始(已删除)评论指出这在 Py3 中不起作用,因为在 Py3 中变成了iteritems()
__getitem__
items()
iteritems()
0赞
jpp
3/9/2018
#3
在我看来,如果您不想索引元组列表,这是一个选项:
from collections import OrderedDict
from itertools import islice
d = OrderedDict(zip(['a', 'b', 'c', 'd'], range(4)))
for each in islice(d.iteritems(), d.keys().index('b'), None):
print(each)
3赞
Mike Müller
3/9/2018
#4
适用于 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
评论
1赞
Mike Müller
3/9/2018
是的,这将是 Python 2 的改进。
0赞
NI6
3/11/2018
我发现这个解决方案最美观、最优雅。与建议的其他产品相比,您会说它也是最有效的吗?
0赞
Mike Müller
3/12/2018
如果您在 Python 2 中使用,则不会进行复制。应该有良好的表现。 在 Python 2 中总是创建一个列表(用于其他解决方案)。这是额外的工作。iteritems()
d.keys()
0赞
Mike Müller
3/12/2018
增加了一些时间。对于此示例,此解决方案是最快的。
评论
if key != 'b': continue
d
d
d
if key in excluded_keys: continue