TypeError:“dict_keys"对象不支持索引

2022-01-31 00:00:00 python python-3.x dictionary

问题描述

def shuffle(self, x, random=None, int=int):"""x, random=random.random -> 随机播放列表 x;返回无.可选 arg random 是一个 0 参数函数,返回一个随机数浮动 [0.0, 1.0);默认情况下,标准 random.random."""randbelow = self._randbelowfor i in reversed(range(1, len(x))):# 在 x[:i+1] 中选择一个元素来交换 x[i]j = randbelow(i+1) if random 是 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.p>

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.

相关文章