python - 如何修复我的代码以使列表索引不超出范围?
问题描述
本质上,我所有的例子都在工作,除了一个。我不知道如何解决它。
def get_nth_tweet(desiredpost: str, stringwanted: int) -> str:
"""This function should return the nth valid tweet in the sequence
of tweets.
Precondition: n >= 0
>>>get_nth_tweet('If the Easter Bunny and the Tooth Fairy had babies would they take your teeth and leave chocolate for you?', 0)
return ('If the Easter Bunny and the Tooth Fairy had babies')
>>>get_nth_tweet('If the Easter Bunny and the Tooth Fairy had babies would they take your teeth and leave chocolate for you?', 23)
return (' ')
"""
n = 50
nth1 = [(desiredpost[i:i+n]) for i in range(0, len(desiredpost), n)]
if stringwanted <= len(nth1):
return nth1[stringwanted]
else:
return ' '
Traceback(最近一次调用最后):文件“x-wingide-python-shell://4600183936/2”,第 46 行,在 testGetNthTweet 文件“x-wingide-python-shell://4600183936/2”,第 72 行,在 _check AssertionError: False is not true : 调用 get_nth_tweet(abcdef,1) 导致错误:列表索引超出范围
解决方案
将第 12 行替换为
if stringwanted < len(nth1):
推荐阅读
- json - 如何在 laravel 中验证递归对象
- python - 如何在进程之间共享日期变量 - 多处理 python
- mule - 如何在 Mule Kernel 中创建小数据集成作业
- node.js - 续集 Postgres 事务问题
- java - 使用集群中的一个节点访问marklogic很慢
- flutter - 如何制作一个BuiltList
不在列表中 飘飘然 - .net-core - NLog 在哪个文件夹中维护日志文件
- java - Google App 引擎本地服务器无法启动
- api - 如何在 erlang API 处理程序中读取表单数据
- c - 如何为 PRO*C 文件启用 ctags。?