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函数时,它会引发以下错误,这是为什么呢?
shuffle
TypeError: 'dict_keys' object does not support indexing
显然,您正在传递d.keys()给shuffle函数。可能是用python2.x编写的(d.keys()返回列表时)。使用python3.x时,d.keys()返回一个dict_keys行为更像a而set不是a的对象list。因此,无法对其进行索引。
d.keys()
dict_keys
set
list
解决方案是将list(d.keys())(或简单地list(d))传递给shuffle。
list(d.keys())
list(d)