类型错误:'dict_keys' 对象不支持索引 [英] TypeError: 'dict_keys' object does not support indexing

查看:35
本文介绍了类型错误:'dict_keys' 对象不支持索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

def shuffle(self, x, random=None, int=int):"""x, random=random.random -> shuffle list x 到位;返回 None.可选的 arg random 是一个返回随机数的 0 参数函数浮动在 [0.0, 1.0);默认情况下,标准 random.random."""randbelow = self._randbelow对于 i in reversed(range(1, len(x))):# 在 x[:i+1] 中选择一个元素来交换 x[i]j = randbelow(i+1) if random is None else int(random() * (i+1))x[i], x[j] = x[j], x[i]

当我运行 shuffle 函数时,它会引发以下错误,这是为什么?

TypeError: 'dict_keys' 对象不支持索引

解决方案

很明显,您正在将 d.keys() 传递给您的 shuffle 函数.可能这是用 python2.x 编写的(当 d.keys() 返回一个列表时).使用 python3.x,d.keys() 返回一个 dict_keys 对象,它的行为更像一个 set 而不是 list.因此,它无法编入索引.

解决方案是将list(d.keys())(或简单的list(d))传递给shuffle.>

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]

When I run the shuffle function it raises the following error, why is that?

TypeError: 'dict_keys' object does not support indexing

解决方案

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.

The solution is to pass list(d.keys()) (or simply list(d)) to shuffle.

这篇关于类型错误:'dict_keys' 对象不支持索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆