首页 > 解决方案 > 如何修复我的代码以使列表索引不超出范围?

问题描述

本质上,我所有的例子都在工作,除了一个。我不知道如何解决它。

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) 导致错误:列表索引超出范围

标签: python

解决方案


将第 12 行替换为

if stringwanted < len(nth1):

推荐阅读