【发布时间】:2018-03-08 17:50:29
【问题描述】:
我正在尝试将此 Python2 代码重写为 Python3 可接受的语法。 .index() 方法会产生以下错误:
AttributeError: 'dict_values' 对象没有属性 'index'
这是因为 .index() 在 Python3 中不是有效的语法。我读过应该使用一个列表来解决这个问题,但我不知道该怎么做。有人知道如何解决这个问题吗?
words1 = [self._word_to_id.keys()[self._word_to_id.values().index(data_x[index])] for index in range(len(puncts) - 1)]
indices = [i for i, w in enumerate(words1) if w in PUNCTUATIONS]
for i in indices:
words1[i], words1[i-1] = words1[i-1], words1[i]
words2 = [self._word_to_id.keys([self._word_to_id.values().index(data_x[index])] for index in range(len(puncts) - 1, len(data_x))]
all_words = words1 + [puncts[-1]] + words2
content = ' '.join(all_words)
min_step = len(puncts)
【问题讨论】:
-
欢迎来到 SO!您能否提供一些可重现(包括所需的输出)代码以便我们测试解决方案?另请阅读minimal reproducible example。
-
self._word_to_id.values().index(....->list(self._word_to_id.values()).index(....摆脱这个错误。但是在这里使用enumerate会使代码更具可读性。另外,你确定是range(len(puncts) - 1(-1)? -
试过了还是不行:
'dict_keys' object does not support indexing
标签: python