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"对象不支持索引


- pytorch 中的自适应池是如何工作的? 2022-07-12
- python-m http.server 443--使用SSL? 2022-01-01
- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
- padding='same' 转换为 PyTorch padding=# 2022-01-01
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- 沿轴计算直方图 2022-01-01
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
- 如何将一个类的函数分成多个文件? 2022-01-01