TypeError:"dict_keys"对象不支持索引 [英] TypeError: 'dict_keys' object does not support indexing
本文介绍了TypeError:"dict_keys"对象不支持索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
def shuffle(self, x, random=None, int=int):
"""x, random=random.random -> shuffle list x in place; return None.
Optional arg random is a 0-argument function returning a random
float in [0.0, 1.0); by default, the standard random.random.
"""
randbelow = self._randbelow
for i in reversed(range(1, len(x))):
# pick an element in x[:i+1] with which to exchange x[i]
j = randbelow(i+1) if random is None else int(random() * (i+1))
x[i], x[j] = x[j], x[i]
当我运行shuffle
函数时,它会引发以下错误,为什么?
When I run the shuffle
function it raises the following error, why is that?
TypeError: 'dict_keys' object does not support indexing
推荐答案
很显然,您要将d.keys()
传递给了shuffle
函数.可能是用python2.x编写的(d.keys()
返回列表时).使用python3.x,d.keys()
返回一个dict_keys
对象,该对象的行为与list
相比更像set
.因此,无法对其进行索引.
Clearly you're passing in d.keys()
to your shuffle
function. Probably this was written with python2.x (when d.keys()
returned a list). With python3.x, d.keys()
returns a dict_keys
object which behaves a lot more like a set
than a list
. As such, it can't be indexed.
解决方案是将list(d.keys())
(或简称为list(d)
)传递给shuffle
.
The solution is to pass list(d.keys())
(or simply list(d)
) to shuffle
.
这篇关于TypeError:"dict_keys"对象不支持索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文