假设我有以下代码:
import collections
d = collections.OrderedDict()
d['foo'] = 'python'
d['bar'] = 'spam'
是否有办法以编号的方式访问这些项目,例如:
d(0) #foo's Output
d(1) #bar's Output
发布于 2018-05-03 16:36:36
>>> 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')
>>> items = list(d.items())
>>> items
[('foo', 'python'), ('bar', 'spam')]
>>> items[0]
('foo', 'python')
>>> items[1]
('bar', 'spam')
发布于 2018-05-03 17:27:37
>>> from sortedcontainers import SortedDict
>>> sd = SortedDict()
>>> sd['foo'] = 'python'
>>> sd['bar'] = 'spam'
>>> print sd.iloc[0] # Note that 'bar' comes before 'foo' in sort order.
'bar'
>>> # If you want the value, then simple do a key lookup:
>>> print sd[sd.iloc[1]]
'python'
https://stackoverflow.com/questions/-100004020
复制相似问题