本文介绍了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"对象不支持索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
The End


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)