如何在不使用 .split 和 .strip 函数的情况下编写自己的拆分函数?



如何编写自己的拆分函数?我只是认为我应该删除空格,'t''n'.但是因为知识匮乏,我没想做这个问题

这是原始问题:

编写一个函数 split(字符串(,返回 给定字符串。单词可以用一个或多个空格分隔' '、制表't'或换行符'n'.

还有例子:

words = split('duff_beer 4.00') # ['duff_beer', '4.00']
words = split('a b cn') # ['a', 'b', 'c']
words = split('tx y n z ') # ['x', 'y', 'z']

限制:不要使用str.split方法!不要使用str.strip方法

关于您的问题的一些评论提供了非常有趣的想法来解决给定限制的问题。

但是假设你不应该使用任何python内置的拆分函数,这是另一个解决方案:

def split(string, delimiters=' tn'):
result = []
word = ''
for c in string:
if c not in delimiters:
word += c
elif word:
result.append(word)
word = ''
if word:
result.append(word)
return result

示例输出:

>>> split('duff_beer 4.00')
['duff_beer', '4.00']
>>> split('a b cn')
['a', 'b', 'c']
>>> split('tx y n z ')
['x', 'y', 'z']

我认为使用正则表达式也是您的最佳选择。

我会尝试这样的事情:

import re
def split(string):
return re.findall('S+',string)

这应该返回字符串中所有无空格字符的列表。

示例输出:

>>> split('duff_beer 4.00')
['duff_beer', '4.00']
>>> split('a b cn')
['a', 'b', 'c']
>>> split('tx y n z ')
['x', 'y', 'z']

一种方法是遍历每个字符,直到找到一个分隔符,从该字符构建一个字符串并将其附加到输出列表中,如下所示:

def split(input_str):
out_list = []
word = ""
for c in input_str:
if c not in ("tn "):
word += c
else:
out_list.append(word)
word = ""
out_list.append(word)
return out_list
a = "pleasensplittme now"
print(split(a))
# will print: ['please', 'split', 'me', 'now']

您可以做的另一件事是使用正则表达式:

import re
def split(input_str):
out_list = []
for m in re.finditer('S+', input_str):
out_list.append(m.group(0))
return out_list
a = "pleasensplittme now"
print(split(a))
# will print: ['please', 'split', 'me', 'now']

正则表达式S+正在查找任何非空格字符序列,函数re.finditer返回一个迭代器,其中包含正则表达式模式的所有非重叠匹配项的 MatchObject 实例。

这是你可以通过分配列表来做的,这是在python3.6上测试

的下面只是一个例子..

values = 'This is a sentence'
split_values = []
tmp  = ''
for words in values:
if words == ' ':
split_values.append(tmp)
tmp = ''
else:
tmp += words
if tmp:
split_values.append(tmp)
print(split_values)

期望输出:

$ ./splt.py
['This', 'is', 'a', 'sentence']

您可以使用以下坚持基础知识的功能,因为您的教授显然更喜欢:

def split(s):
output = []
delimiters = {' ', 't', 'n'}
delimiter_found = False
for c in s:
if c in delimiters:
delimiter_found = True
elif output:
if delimiter_found:
output.append('')
delimiter_found = False
output[-1] += c
else:
output.append(c)
return output

因此:

print(split('duff_beer 4.00'))
print(split('a b cn'))
print(split('tx y n z '))

将输出:

['duff_beer', '4.00']
['a', 'b', 'c']
['x', 'y', 'z']

请找到我的解决方案,它不是最好的解决方案,但它有效:

def convert_list_to_string(b):
localstring=""
for i in b:
localstring+=i
return localstring
def convert_string_to_list(b):
locallist=[]
for i in b:
locallist.append(i)
return locallist
def mysplit(inputString, separator):
listFromInputString=convert_string_to_list(inputString)
part=[]
result=[]
j=0
for i in range(0, len(listFromInputString)):
if listFromInputString[i]==separator:
part=listFromInputString[j:i]
j=i+1
result.append(convert_to_string(part))
else:
pass
if j != 0:
result.append(convert_to_string(listFromInputString[j:]))
if len(result)==0:
result.append(inputString)
return result

测试:

mysplit("deesdfedefddfssd", 'd')
结果: [", "ees", "fe", "ef", ", ">

fss", "]

您的一些解决方案非常好,但在我看来,除了使用该函数之外,还有更多替代选项:

values = 'This is a sentence'
split_values = []
tmp = ''
for words in values:
if words == ' ':
split_values.append(tmp)
tmp = ''
else:
tmp += words
if tmp:
split_values.append(tmp)
print(split_values)

这里的a是字符串,s是模式。

a="Tapas Pall Tapas TPal TapP al Pala"
s="Tapas"
def fun(a,s):
st=""
l=len(s)
li=[]
lii=[]
for i in range(0,len(a)):
if a[i:i+l]!=s:
st=st+a[i]
elif i+l>len(a):
st=st+a[i]
else:
li.append(st)
i=i+l
st=""
li.append(st)
lii.append(li[0])
for i in li[1:]:
lii.append(i[l-1:])
return lii
print(fun(a,s))
print(a.split(s))    

这将处理字符串中的空格并返回空列表(如果存在(

def mysplit(strng):
#
# put your code here
#
result = []
words = ''

for char in strng:
if char != ' ':
words += char
else:
if words:
result.append(words)
words = ''


result.append(words)

for item in result:
if item == '':
result.remove(item)

return result
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(""))
def mysplit(strng):
my_string = ''
liste = []
for x in range(len(strng)):
my_string += "".join(strng[x])
if strng[x] == ' ' or x+1 == len(strng):
liste.append(my_string.strip())
my_string = ''
liste = [elem for elem in liste if elem!='']
return liste

编码之前提供算法总是一个好主意: 这是在分隔符上拆分单词的过程,而无需使用任何 python 内置方法或函数:

    初始化一个名为 result 的空列表
  1. [],它将用于保存结果的单词列表,以及一个名为word = ">字符串,它将用于连接每个字符串块。

  2. 只要没有达到分隔符,就继续添加字符串字符

  3. 当您到达分隔符并且len(word( = 0时,不要执行下面的任何操作。只需转到下一个迭代即可。这将有助于检测和删除前导空格

  4. 当你到达分隔符,并且len(word( != 0时,将单词附加到结果,重新初始化单词并跳转到下一个迭代,而不执行以下任何操作

  5. 返回结果


def my_split(s, delimiter = [" ","t"]): 
result,word = [], "" # Step 0

N = len(s)
for i in range(N) : #
if N == 0:#  Case of empty string
return result
else: # Non empty string        

if s[i] in delimiter and len(word) == 0: # Step 2     
continue # Step 2: Skip, jump to the next iteration
if s[i] in delimiter and len(word) != 0: # Step 3        
result.append(word) # Step 3
word = "" # Step 3
continue # Step 3: Skip, jump to the next iteration          

word = word + s[i] # Step 1.


return result
print(my_split("        how are    you?  please split me now!       "))

以上所有答案都很好,有一个类似的解决方案,有一个额外的空列表。

def my_split(s):
l1 = []
l2 = []
word = ''
spaces = ['', 't', ' ']
for letters in s:
if letters != ' ':
word += letters
else:
l1.append(word)
word = ''
if word:
l1.append(word)
for words in l1:
if words not in spaces:
l2.append(words)
return l2

my_string = '       The old fox jumps into the deep river'
y = my_split(my_string)
print(y)

最新更新