简体   繁体   English

排序(string,float)的字典时,字符串索引超出范围

[英]String index out of range when sorting a dictionary of (string, float)

I have a dictionary mapping strings to floats that I want to sort. 我有一个字典,将字符串映射到要排序的浮点数。 I can verify that the types of the values are correct, but when I try the sort I get an IndexError execption. 我可以验证值的类型正确,但是当我尝试排序时,我得到了IndexError执行。

Below is a code snippet. 下面是一个代码片段。 The validation loop runs fine and then the call to sorted fails. 验证循环运行良好,然后对sorted的调用失败。

for k, v in metric.items():
    if not isinstance(v, float):
        print "Bad value %s for %s" % (k, str(v))
rank = sorted(metric, key=operator.itemgetter(1), reverse=True)


---> 10     rank = sorted(metric, key=operator.itemgetter(1), reverse=True)
     11 

IndexError: string index out of range

Any idea why this happens? 知道为什么会这样吗?

Edit: this passes too with no problem: 编辑:这也顺利通过了:

for h in metric.iteritems():
    if not isinstance(operator.itemgetter(1)(h), float):
        print "Bad value %s for %s" % (h[0], h[1])

You are only sorting the keys of the dictionary. 您只对字典的排序。 Apparently some of your keys are only 1 character short, so you get an index error for key[1] (which is what operator.itemgetter(1)(key) would try and access). 显然,您的某些键仅短1个字符,因此您会得到key[1]的索引错误(这是operator.itemgetter(1)(key)会尝试访问的错误)。

If the expected output is a sorted sequence of keys, look up the value from the dictionary: 如果期望的输出是键的排序序列,请从字典中查找值:

rank = sorted(metric, key=metric.get, reverse=True)

If you expected a sequence of (key, value) pairs, sort metric.items() : 如果您期望一系列(key, value)对,请对metric.items()排序:

rank = sorted(metric.items(), key=operator.itemgetter(1), reverse=True)

When sorting the dict.items() sequence, item[1] refers to the value. dict.items()序列进行排序时, item[1]引用该值。

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

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