简体   繁体   English

遍历有序字典,就好像它是一个列表一样

[英]Iterating through an ordered dictionary as if it were a list

I have this ordered dictionary: 我有这个命令字典:

numerals = collections.OrderedDict([('I', 1),('V', 5),('X', 10),('L', 50),
                                    ('C', 100),('D', 500),('M', 1000)])

And I want to write a function which creates the rule for numerals, that 'I' can only be subtracted from 'V' and 'X', 'X' can only be subtracted from 'L' and 'C', and 'C' can only be subtracted from 'D' and 'M'. 我想编写一个为数字创建规则的函数,即只能从“ V”和“ X”中减去“ I”,只能从“ L”,“ C”和“ C”中减去“ X” '只能从'D'和'M'中减去。 If it were a list, I could make a simple rule that elements with an even-numbered index can be subtracted from the two consecutive elements of the list. 如果是列表,我可以做一个简单的规则,即可以从列表的两个连续元素中减去索引为偶数的元素。 However, as dictionaries aren't indexed I'm not sure how I would go about this. 但是,由于字典没有被索引,所以我不确定该如何处理。 Is there an equivalent way of making that rule using a list, but using a dictionary instead? 是否有使用列表创建规则但使用字典的等效方法?

You could call enumerate on the OrdereDdict to generate indices for each key-value pair in the dictionary: 您可以在OrdereDdict上调用enumerate为字典中的每个键值对生成索引:

>>> for index, key in enumerate(numerals):
...    print(index, key, numerals[key])
...
0 I 1
1 V 5
2 X 10
3 L 50
4 C 100
5 D 500
6 M 1000 

You would then use the generated index values to differentiate key-value pairs at even indices from those at odd valued indices. 然后,您将使用生成的索引值来区分偶数索引处的键值对与奇数索引处的键值对。

It's somewhat inefficient, but you could do create a mapping function as shown to lookup random indices on-the-fly. 它效率不高,但是您可以创建一个映射函数,如图所示,以实时查找随机索引。 If you're doing to do it a lot, it could be optimized to not recreate the rev_map everytime it was called. 如果您要做很​​多事情,可以对其进行优化, rev_map每次调用rev_map时都重新创建它。

import collections

numerals = collections.OrderedDict([('I', 1),('V', 5),('X', 10),('L', 50),
                                    ('C', 100),('D', 500),('M', 1000)])

def index_to_key(od, index):
    rev_map = {i:k for i,k in enumerate(od.keys())}
    return rev_map[index]

for i in range(len(numerals)):
    key = index_to_key(numerals, i)
    value = numerals[key]
    print('numerals[{}]: key: {!r}, value: {}'.format(i, key, value))

Output: 输出:

numerals[0]: key: 'I', value: 1
numerals[1]: key: 'V', value: 5
numerals[2]: key: 'X', value: 10
numerals[3]: key: 'L', value: 50
numerals[4]: key: 'C', value: 100
numerals[5]: key: 'D', value: 500
numerals[6]: key: 'M', value: 1000

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM