最后一个单词未添加到列表中。

huangapple go评论81阅读模式
英文:

Last word is not appending in the list

问题

以下是已更正的代码:

def splitstring(s):
    a = []
    count = ''
    for i in s:
        if i == ' ':
            if count:
                a.append(count)
                count = ''
        else:
            count += i
    if count:
        a.append(count)
    return a

# 输入 = 'Hello World'
# 期望输出 = ['Hello', 'World']
# 实际输出 = ['Hello', 'World']

这个更正后的代码会将字符串中的单词分割并添加到列表中,包括最后一个单词。

英文:

I wrote the code of returning the words in a string into a list. But the code is not appending the last word in the string. Here I tried to replicate the split() method for strings. What will be the corrected code?

def splitstring(s):
    a = []
    count = ''
    for i in s:
        if i == ' ':
            a.append(count)
            count = ''
        else:
            count += i
    return a

# Input = 'Hello World'
# Expected output = ['Hello', 'World']
# Actual = ['Hello']

答案1

得分: 1

你目前的实现无法处理字符串中的最后一个单词,因为它只在遇到空格时将单词附加到列表中。
要解决这个问题,你可以这样做:

def splitstring(s):
    a = []
    count = ''
    for i in s:
        if i == ' ':
            a.append(count)
            count = ''
        else:
            count += i
    if count:  # 添加这个条件以处理最后一个单词
        a.append(count)
    return a

尽管如此,我建议你使用Python内置的函数。它们经过优化且可靠。

英文:

Your current implementation doesn't handle the last word in the string, because it only appends the word to the list when it encounters a space.
To fix this problem, you can do this:

def splitstring(s):
    a = []
    count = ''
    for i in s:
        if i == ' ':
            a.append(count)
            count = ''
        else:
            count += i
    if count:  # Add this condition to handle the last word
        a.append(count)
    return a

Though, I suggest you to use Python's built-in functions. They are well optimized and reliable.

答案2

得分: 0

你没有任何与 if i == ' ': 的第二个匹配项。

快速修复:

def splitstring(s):
    a = []
    count = ''
    for i in s:
        if i == ' ':
            a.append(count)
            count = ''
        else:
            count += i
    a.append(count)
    return a
英文:

You don't have any second match for if i == ' ':.

Quick fix:

def splitstring(s):
    a = []
    count = ''
    for i in s:
        if i == ' ':
            a.append(count)
            count = ''
        else:
            count += i
    a.append(count)
    return a

huangapple
  • 本文由 发表于 2023年7月23日 17:13:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76747456.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定