【问题标题】:TypeError: list indices must be integers or slices, not stringTypeError:列表索引必须是整数或切片,而不是字符串
【发布时间】:2019-02-22 12:59:01
【问题描述】:

所以我在尝试运行以下代码时遇到了这个错误,我首先认为可能是我没有正确地将字符串转换为列表,但在我看来这是正确的或者我错了? ,谢谢。

这是我要运行代码的内容:

u0 +++$+++ u2 +++$+++ m0 +++$+++ ['L194', 'L195', 'L196', 'L197']

u0 +++$+++ u2 +++$+++ m0 +++$+++ ['L198', 'L199']

u0 +++$+++ u2 +++$+++ m0 +++$+++ ['L200', 'L201', 'L202', 'L203']

u0 +++$+++ u2 +++$+++ m0 +++$+++ ['L204', 'L205', 'L206']

u0 +++$+++ u2 +++$+++ m0 +++$+++ ['L207', 'L208']

conversations_fields = ['Character_one_ID' , 'Character_two_ID' , 'Movie_ID' , 'utteranceIDs']
conversations = []
with open("./cornell movie-dialogs corpus/movie_conversations.txt", 'r', encoding='iso-8859-1') as f:
    for line in f:
        values = line.split(" +++$+++ ")
        # Extract fields
        convObj = {}
        for i, field in enumerate(conversations_fields):
            convObj[field] = values[i]
        # Convert string to list (convObj["utteranceIDs"] == "['L598485', 'L598486', ...]")
        lineIds = eval(convObj["utteranceIDs"])
        # Reassemble lines
        convObj['lines'] = []
        for lineId in lineIds:
            convObj['lines'].append(lines[lineId]
        conversations.append(convObj)

TypeError Traceback(最近一次调用最后一次)

 <ipython-input-34-d7002161f69c> in <module>()

 13         convObj['lines'] = []
 14         for lineId in lineIds:
 ---> 15             convObj['lines'].append(lines[lineId])
 16         conversations.append(convObj)

TypeError: 列表索引必须是整数或切片,而不是 str

【问题讨论】:

标签: python string list type-conversion


【解决方案1】:

lineIds = convObj['utteranceIDs'] 填充有"['L194', 'L195', 'L196', 'L197']"eval - 见Why is using 'eval' a bad practice?

   lineIds = eval(convObj["utteranceIDs"])

lineIds 是一个字符串列表,lineID 也是一个字符串("L194" 然后"L195" 等等...) - 你不能用它来索引@987654330 @:

   for lineId in lineIds:
       convObj['lines'].append(lines[lineId])   # you also missed a ) here  

【讨论】:

  • 谢谢你,现在我明白了,我会改变方法。
猜你喜欢
  • 2017-11-20
  • 2016-09-16
  • 1970-01-01
  • 2019-07-04
  • 2015-12-09
  • 2021-11-28
  • 2020-09-23
  • 2020-09-04
相关资源
最近更新 更多