Python中文
首页
教程
问答
标签
搜索
登录
注册
Python IndexError string index out of range Beginner
回答此问题可获得
20
贡献值,回答如果被采纳可获得
50
分。
<p>所以对于一个编程任务,我们必须用python重写sort函数来对单词列表进行排序。到目前为止,我已经使它能够根据每个单词的第一个字母对单词进行排序,现在我试着运行递归,以便在第一个字母或任何一个字母相同的情况下仍然对其进行排序。我遇到了“索引器错误:字符串索引超出范围”错误。到目前为止我得到的是</p> <pre><code>def insertion_sort(bookwords): for index in range(1,len(bookwords)): global word word=bookwords[index] i=index-1 word_checker(bookwords, 0, i) def word_checker(bookwords, num, i): while i>=0: wordleft=bookwords[i] if ord(word[num])<ord(wordleft[num]): bookwords[i+1]=bookwords[i] bookwords[i]=word i=i-1 elif ord(word[num])==ord(wordleft[num]): num=num+1 word_checker(bookwords, num, i) else: break bookwords=["michael", "maddy", "michelle", "monstor", "money", "mountain", "miniscus", "mega"] insertion_sort(bookwords) print bookwords </code></pre> <p>我猜num正在变得比单词更大,但是当字母arn不一样的时候,它运行了很多次而没有停止,所以我有点困惑它为什么这么做。任何帮助都将不胜感激</p> <p>更新</p> <p>好了,现在它可以工作了,但是当我把它放到提供的代码中测试它有多快,大约700000个单词,它持续了30+,直到我停止它,因为sort函数花了5秒。这是我的代码</p> ^{pr2}$
0 条评论
分类:
Python问答
请先
登录
后评论
默认排序
时间排序
1 个回答
匿名
1天前
擅长:python、mysql、java
<p>几件事:</p> <ul> <li>pythonzero索引字符串(因此从0到len(string)-1)。 以及</li> <li>考虑使用“for”来浏览每个字母。在</li> </ul>
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
如何添加虚拟方法
2 回答
如何添加表示整数的擦边字符串?
4 回答
如何添加要在Bokeh中使用的新font.ttf文件?
9 回答
如何添加要显示的矩阵XY轴编号和XY轴
2 回答
如何添加计数?
3 回答
如何添加计数器函数?
4 回答
如何添加计数器列来计算数据帧中另一列中的特定值?
10 回答
如何添加计数器来跟踪while循环中的月份和年份?
6 回答
如何添加计数并删除countplot的顶部和右侧脊椎?
2 回答
如何添加计时器wx.应用程序更新窗口对象的主循环?
3 回答
如何添加评论到帖子?PostDetailVew,Django 2.1.5
3 回答
如何添加评论拉梅尔亚姆
3 回答
如何添加诸如矩阵Python/Pandas之类的数据帧?
8 回答
如何添加谷歌地点自动完成到Flask?
6 回答
如何添加超时、python discord bot
2 回答
如何添加超过1dp的检查
3 回答
如何添加距离方法
10 回答
如何添加跟随游戏的敌人精灵
2 回答
如何添加路径以便python可以找到程序?
3 回答
如何添加身份验证/安全性以使用happybase访问HBase?
10 回答