【问题标题】:How to iterate a python dictionary (d = {}) starting with index s如何从索引s开始迭代python字典(d = {})
【发布时间】:2014-03-04 22:54:14
【问题描述】:

我有一本字典,我需要从 index 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 loops for-loop dictionary indexing


【解决方案1】:

字典在 python 中是未排序的。这是因为字典是哈希表,它们是根据索引哈希“排序”的。因此,它们也不能像列表或字符串那样被切片(即seq[i:j])。用更专业的术语来说,字典是 Mappings,而列表、字符串、元组等是 Sequence 类型。只有从 Sequences 派生的类型才能被切片。

您可以为此目的使用collections.OrderedDict。它会记住项目添加到字典中的顺序,并允许您像列表一样对其进行迭代。

或者在您的具体示例中可能只是一个列表。

【讨论】:

  • 我在这里更正了d1 = collections.OrderedDict(),但还是出现了同样的错误
  • 您不能直接对OrderedDict 进行切片。与访问字典元素一样,您需要先使用.values().keys().items()。不同之处在于这些视图是有序的。例如,for key, value in d1.items()[s:]
【解决方案2】:

字典的索引是无序的,因为它们是哈希表。如果你想从某个键迭代它,我建议你创建一个函数“cmp”来定义一个订单。

def cmp(a,b):
    if a<b:
        return 1
    else:
        return -1

d={ i:1.0/i for i in range(1,10) }

for i in sorted(d.keys(),cmp)[3:]:
    print i,d[i]

这是一个例子。希望对你有帮助。

【讨论】:

  • 那个 cmp 函数毫无意义。这项工作由sorted 在这里完成,并且与for i in sorted(d.keys())[3:]: 一样好。
  • Daniel Roseman 非常感谢 sorted(d.keys())[3:] 你帮了我很多,这正是我所需要的。
  • @DanielRoseman,不,cmp 功能很重要。您可以删除它并仅使用排序。看看会发生什么。希望你能接受我的回答。
猜你喜欢
  • 2020-08-09
  • 2013-07-21
  • 1970-01-01
  • 2014-01-15
  • 1970-01-01
  • 2019-05-25
  • 2011-09-03
  • 2017-11-13
  • 1970-01-01
相关资源
最近更新 更多