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

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

Last word is not appending in the list

问题

以下是已更正的代码:

  1. def splitstring(s):
  2. a = []
  3. count = ''
  4. for i in s:
  5. if i == ' ':
  6. if count:
  7. a.append(count)
  8. count = ''
  9. else:
  10. count += i
  11. if count:
  12. a.append(count)
  13. return a
  14. # 输入 = 'Hello World'
  15. # 期望输出 = ['Hello', 'World']
  16. # 实际输出 = ['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?

  1. def splitstring(s):
  2. a = []
  3. count = ''
  4. for i in s:
  5. if i == ' ':
  6. a.append(count)
  7. count = ''
  8. else:
  9. count += i
  10. return a
  11. # Input = 'Hello World'
  12. # Expected output = ['Hello', 'World']
  13. # Actual = ['Hello']

答案1

得分: 1

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

  1. def splitstring(s):
  2. a = []
  3. count = ''
  4. for i in s:
  5. if i == ' ':
  6. a.append(count)
  7. count = ''
  8. else:
  9. count += i
  10. if count: # 添加这个条件以处理最后一个单词
  11. a.append(count)
  12. 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:

  1. def splitstring(s):
  2. a = []
  3. count = ''
  4. for i in s:
  5. if i == ' ':
  6. a.append(count)
  7. count = ''
  8. else:
  9. count += i
  10. if count: # Add this condition to handle the last word
  11. a.append(count)
  12. return a

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

答案2

得分: 0

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

快速修复:

  1. def splitstring(s):
  2. a = []
  3. count = ''
  4. for i in s:
  5. if i == ' ':
  6. a.append(count)
  7. count = ''
  8. else:
  9. count += i
  10. a.append(count)
  11. return a
英文:

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

Quick fix:

  1. def splitstring(s):
  2. a = []
  3. count = ''
  4. for i in s:
  5. if i == ' ':
  6. a.append(count)
  7. count = ''
  8. else:
  9. count += i
  10. a.append(count)
  11. 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:

确定