shuffle list x in plac-6ren">
gpt4 book ai didi

python - 类型错误 : 'dict_keys' object does not support indexing

转载 作者:IT老高 更新时间:2023-10-28 12:32:11 25 4
gpt4 key购买 nike

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 函数时,它会引发以下错误,这是为什么呢?

TypeError: 'dict_keys' object does not support indexing

最佳答案

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

解决办法是通过list(d.keys()) (或简单地说 list(d) )到 shuffle .

关于python - 类型错误 : 'dict_keys' object does not support indexing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17322668/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com