【问题标题】:Error: IndexError: string index out of range. Trying to reverse the order of a list [duplicate]错误:IndexError:字符串索引超出范围。试图颠倒列表的顺序[重复]
【发布时间】:2017-06-03 00:31:42
【问题描述】:

我正在解决“适用于所有人的 Python”第 7 章中的一个问题。该程序旨在获取一个文件并以相反的字符顺序重现该文件。这段代码列出了出现的字符,但是当我使用时:

reversedList = sorted(charList, key=itemgetter(1), reverse=True)

我得到:IndexError:字符串索引超出范围。这是完整的代码:

from _operator import itemgetter

def main():
     file = input("Enter the name of the file to be reversed: ")
     file = open(file, "r")
     charList = []
     char = file.read(1)
     charList.append(char[0])
     while char != "" :
        char = file.read(1)
        charList.append(char)

     reversedList = sorted(charList, key=itemgetter(1), reverse=True)
     file.close()

main()

请让我知道这里出了什么问题。

【问题讨论】:

  • charList = file.read()[::-1] 在这里工作正常。无需逐字符读取。

标签: python list


【解决方案1】:

我不明白你为什么要排序,你可以简单地使用:

reversedList = charList[::-1]

[::-1] 反转列表、元组等

itemgetter(..) 在这里不起作用,因为它与您想要的相反:itemgetter(value) 生成一个函数,该函数需要 list 并返回 value 的索引,但 @987654326 @ 不期望函数将列表映射到索引,它期望函数将元素转换为要排序的指标。

可行但非常有效的方法是:

sorted(charList, key=charList.index, reverse=True)

尽管如此,我认为这本书不希望你使用sorted,如果你想自己编写一个反向函数,你可以使用例如:

reversedList = []
for i in range(len(charList)-1,-1,-1):
    reversedList.append(charList[i])

【讨论】:

  • 谢谢你,我知道一定有更简单的方法。
猜你喜欢
  • 2021-07-23
  • 1970-01-01
  • 2015-01-28
  • 2017-03-26
  • 2022-09-27
  • 2012-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多