TypeError: #39;dict_keys#39; object does not support indexing(TypeError:“dict_keys对象不支持索引)
问题描述
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.
这篇关于TypeError:“dict_keys"对象不支持索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:TypeError:“dict_keys"对象不支持索引
基础教程推荐
- 对多索引数据帧的列进行排序 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
