按索引访问 collections.OrderedDict 中的项目 [英] Accessing items in an collections.OrderedDict by index

查看:34
本文介绍了按索引访问 collections.OrderedDict 中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下代码:

导入集合d = collections.OrderedDict()d['foo'] = '蟒蛇'd['bar'] = '垃圾邮件'

有没有办法以编号的方式访问项目,例如:

d(0) #foo 的输出d(1) #bar 的输出

解决方案

如果它是 OrderedDict(),您可以通过获取 (key,value) 对的元组作为索引轻松访问元素关注

<预><代码>>>>进口藏品>>>d = collections.OrderedDict()>>>d['foo'] = '蟒蛇'>>>d['bar'] = '垃圾邮件'>>>d.items()[('foo', 'python'), ('bar', '垃圾邮件')]>>>d.items()[0]('foo', '蟒蛇')>>>d.items()[1]('bar', '垃圾邮件')

Python 3.X 的注意事项

dict.items 将返回一个 可迭代的 dict 视图对象 而不是列表.我们需要将调用包装到一个列表中,以使索引成为可能

<预><代码>>>>项目 = 列表(d.items())>>>项目[('foo', 'python'), ('bar', '垃圾邮件')]>>>项目[0]('foo', '蟒蛇')>>>项目[1]('bar', '垃圾邮件')

Lets say I have the following code:

import collections
d = collections.OrderedDict()
d['foo'] = 'python'
d['bar'] = 'spam'

Is there a way I can access the items in a numbered manner, like:

d(0) #foo's Output
d(1) #bar's Output

解决方案

If its an OrderedDict() you can easily access the elements by indexing by getting the tuples of (key,value) pairs as follows

>>> import collections
>>> d = collections.OrderedDict()
>>> d['foo'] = 'python'
>>> d['bar'] = 'spam'
>>> d.items()
[('foo', 'python'), ('bar', 'spam')]
>>> d.items()[0]
('foo', 'python')
>>> d.items()[1]
('bar', 'spam')

Note for Python 3.X

dict.items would return an iterable dict view object rather than a list. We need to wrap the call onto a list in order to make the indexing possible

>>> items = list(d.items())
>>> items
[('foo', 'python'), ('bar', 'spam')]
>>> items[0]
('foo', 'python')
>>> items[1]
('bar', 'spam')

这篇关于按索引访问 collections.OrderedDict 中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆