问题:TypeError:“ dict_keys”对象不支持索引

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函数时,它会引发以下错误,这是为什么呢?

TypeError: 'dict_keys' object does not support indexing
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

回答 0

显然,您正在传递d.keys()shuffle函数。可能是用python2.x编写的(d.keys()返回列表时)。使用python3.x,d.keys()返回一个dict_keys对象,其行为更像a而set不是alist。因此,无法对其进行索引。

解决方案是将list(d.keys())(或简单地list(d))传递给shuffle

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.


回答 1

您将把结果传递somedict.keys()给函数。在Python 3中,dict.keys它不返回列表,但是代表字典键视图的(类似于集合)的类似集合的对象不支持索引。

要解决此问题,请使用list(somedict.keys())来收集密钥并进行处理。

You’re passing the result of somedict.keys() to the function. In Python 3, dict.keys doesn’t return a list, but a set-like object that represents a view of the dictionary’s keys and (being set-like) doesn’t support indexing.

To fix the problem, use list(somedict.keys()) to collect the keys, and work with that.


回答 2

将迭代器转换为列表可能会产生成本。相反,要获得第一项,可以使用:

next(iter(keys))

或者,如果要遍历所有项目,则可以使用:

items = iter(keys)
while True:
    try:
        item = next(items)
    except StopIteration as e:
        pass # finish

Convert an iterable to a list may have a cost. Instead, to get the the first item, you can use:

next(iter(keys))

Or, if you want to iterate over all items, you can use:

items = iter(keys)
while True:
    try:
        item = next(items)
    except StopIteration as e:
        pass # finish

回答 3

为什么需要在已经存在的情况下实施改组?留在巨人的肩膀上。

import random

d1 = {0:'zero', 1:'one', 2:'two', 3:'three', 4:'four',
     5:'five', 6:'six', 7:'seven', 8:'eight', 9:'nine'}

keys = list(d1)
random.shuffle(keys)

d2 = {}
for key in keys: d2[key] = d1[key]

print(d1)
print(d2)

Why you need to implement shuffle when it already exists? Stay on the shoulders of giants.

import random

d1 = {0:'zero', 1:'one', 2:'two', 3:'three', 4:'four',
     5:'five', 6:'six', 7:'seven', 8:'eight', 9:'nine'}

keys = list(d1)
random.shuffle(keys)

d2 = {}
for key in keys: d2[key] = d1[key]

print(d1)
print(d2)

回答 4

在Python 2中,dict.keys()返回一个列表,而在Python 3中,它返回一个生成器。

您只能遍历其值,否则可能必须将其显式转换为列表,即将其传递给列表函数。

In Python 2 dict.keys() return a list, whereas in Python 3 it returns a generator.

You could only iterate over it’s values else you may have to explicitly convert it to a list i.e. pass it to a list function.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。