我有一个字典,我需要从索引s(而不是第一个)开始迭代字典。我这样写

def _get_cell_end_offset(self, d, s, n):
        for e in d[s:]:
            if e != 0 and d[e][0][1] == ".ends" and d[s][1][1] == n:
                return e


创建了字典,所以这d = {},我添加了元素,所以d[i] = l

但结果是出现类似

"Traceback (most recent call last):
  File "./main.py", line 23, in <module>
    ss = netlist._get_cell_end_offset(s, 9, "NR2_V20_2")
  File "/home/ubuntu/synop/net.py", line 16, in _get_cell_end_offset
    for e in d[s:]:
TypeError: unhashable type"


我的这类字典

(1, [['START', '.SUBCKT'], ['PIN', 'NR2_V20_1'], ['PIN', 'VDD'], ['PIN', 'VSS'], ['PIN', 'VBP'], ['PIN', 'VBN'], ['PIN', 'X'], ['PIN', 'A1'], ['PIN', 'A2']])
(2, [['ELEMENT', 'R1'], ['PIN', 'X:F93'], ['PIN', 'X:195'], ['PIN', '6.014590e+00']])
(3, [['ELEMENT', 'Cg15'], ['PIN', 'ln_N_76:291'], ['PIN', 'VSS'], ['PIN', '2.133320e-17']])
.........................................................................................
.........................................................................................
.........................................................................................


该怎么办?

最佳答案

字典在python中未排序。这是因为字典是哈希表,并且根据索引哈希对其进行“排序”。因此,它们也无法像列表或字符串一样被切片(即seq[i:j])。用更专业的词来说,字典是Mappings,而列表,字符串,元组等是Sequence类型。只能切片从“序列”派生的类型。

您可以将collections.OrderedDict用于此目的。它记住项目以什么顺序添加到字典中,并允许您像列表一样遍历字典。

在您的特定示例中,可能只是一个列表。

关于python - 如何从索引s开始迭代python字典(d = {}),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21629264/

10-11 23:07
查看更多