gat*_*007 135 python dictionary python-3.x
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]
Run Code Online (Sandbox Code Playgroud)
When I run the shuffle function it raises the following error, why is that?
TypeError: 'dict_keys' object does not support indexing
Run Code Online (Sandbox Code Playgroud)
mgi*_*son 221
很明显,你正在传递d.keys()你的shuffle功能.可能这是用python2.x编写的(当d.keys()返回列表时).使用python3.x,d.keys()返回dict_keys一个set比a 更像的对象list.因此,它无法编入索引.
解决方案是通过list(d.keys())(或简单地list(d))shuffle.
use*_*342 11
您将结果传递somedict.keys()给函数.在Python 3中,dict.keys不返回列表,但是类似于集合的对象表示字典键的视图并且(类似于集合)不支持索引.
要解决此问题,请使用list(somedict.keys())收集密钥并使用它.
将iterable转换为列表可能会产生成本.相反,要获得第一个项目,您可以使用:
next(iter(keys))
Run Code Online (Sandbox Code Playgroud)
或者,如果要迭代所有项目,可以使用:
items = iter(keys)
while True:
try:
item = next(items)
except StopIteration as e:
pass # finish
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
107097 次 |
| 最近记录: |