我应该编写这段代码,以便它从字符串返回一个列表,我想这样做而不需要重复使用 list() 或 split() 函数,但尝试编写我自己的函数,模仿 split( ), 但仅由空格分隔。
代码如下:
def mysplit(strng):
res = []
word = ""
for i in range(len(strng)):
if strng[i] != " ":
word += strng[i]
else:
res.append(word)
word = ""
if len(res) > 0:
return res
else:
return []
#These below are tests.
print(mysplit("To be or not to be, that is the question"))
print(mysplit("To be or not to be,that is the question"))
print(mysplit(" "))
print(mysplit(" abc "))
print(mysplit(""))
这是预期的输出:
['To', 'be', 'or', 'not', 'to', 'be,', 'that', 'is', 'the', 'question']
['To', 'be', 'or', 'not', 'to', 'be,that', 'is', 'the', 'question']
[]
['abc']
[]
这就是我得到的:
['To', 'be', 'or', 'not', 'to', 'be,', 'that', 'is', 'the']
['To', 'be', 'or', 'not', 'to', 'be,that', 'is', 'the']
['', '', '']
['', 'abc']
[]
它不会将最后一个单词附加到结果列表中,因为最后一个单词后没有空格字符。要解决此问题,您可以在循环后添加额外的检查,以将最后一个单词附加到结果列表(如果它不为空)。
def mysplit(strng):
res = []
word = ""
for i in range(len(strng)):
if strng[i] != " ":
word += strng[i]
else:
if word: # Add this check to avoid appending empty words
res.append(word)
word = ""
if word: # Add this check to append the last word if it's not empty
res.append(word)
return res
print(mysplit("To be or not to be, that is the question"))
print(mysplit("To be or not to be,that is the question"))
print(mysplit(" "))
print(mysplit(" abc "))
print(mysplit(""))
结果:
['To', 'be', 'or', 'not', 'to', 'be,', 'that', 'is', 'the', 'question']
['To', 'be', 'or', 'not', 'to', 'be,that', 'is', 'the', 'question']
[]
['abc']
[]
你不需要 range() 因为你可以遍历源字符串而不用担心它的长度。像这样的东西:
def mysplit(s):
words = ['']
for c in s:
if c == ' ':
if words[-1]:
words.append('')
else:
words[-1] += c
return words if words[-1] else words[:-1]
print(mysplit("To be or not to be, that is the question"))
print(mysplit("To be or not to be,that is the question"))
print(mysplit(" "))
print(mysplit(" abc "))
print(mysplit(""))
输出:
['To', 'be', 'or', 'not', 'to', 'be,', 'that', 'is', 'the', 'question']
['To', 'be', 'or', 'not', 'to', 'be,that', 'is', 'the', 'question']
[]
['abc']
[]