我在Python中遇到了一个列表退出错误。

3

我是一名初学者Python程序员,我开始在Codewars上练习,遇到了以下任务:

编写一个函数,将字符串拆分成每两个字符一组。如果字符串长度为奇数,则用下划线填充最后一组的第二个字符。

solution('abc') #应返回 ['ab', 'c_'] solution('abcdef') #应返回 ['ab', 'cd', 'ef']

下面是我的代码,可以给出正确结果:

def solution(s):
    l = [s[i:i+2] for i in range(0,len(s) ,2)]
    if len(l[-1]) == 1:
        l[-1] += "_"
    return l

print(solution('abc')) -> ['ab', 'c_']
print(solution('asdfadsf')) -> ['as', 'df', 'ad', 'sf']

但是当我将代码提交到 Code Wars 时,我收到了以下错误提示:
if len(l[-1]) == 1: IndexError: list index out of range

如果我在Visual Studio Code中测试,就不会出现这种错误。

请问有人可以解释一下如何修复这个问题吗? 谢谢!!:)


2
你需要处理 solution('') 这种情况吗? - Mark
哇!你的修复起作用了!!谢谢你!!! - Michael Ben Haym
啊,这一行修复了索引错误,因为在此之前它尝试从一个空列表中取出索引? - Michael Ben Haym
1个回答

2
问题出在对于输入的空字符串''l[-1]无法被访问。在这种情况下,列表推导式返回一个空列表[],该列表没有l[-1]元素。
需要单独检查空字符串输入:
def solution(s): 
    if not s: 
        return []

    l = [s[i:i+2] for i in range(0,len(s) ,2)]
    if len(l[-1]) == 1:
        l[-1] += "_"
    return l

print(solution('abc')) # -> ['ab', 'c_']
print(solution('asdfadsf')) # -> ['as', 'df', 'ad', 'sf']

print(solution('')) # -> [] 

1
所以这行代码修复了索引错误,因为在此之前它尝试从一个空列表中获取索引。 - Michael Ben Haym
@Michael 确切无误 - Patrick Artner
@MichaelBenHaym,如果答案有帮助,请再次确认接受。 - Lukasz Tracewski

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接