Python 我需要这个子字符串计数程序来返回元组
我已经想出了这段代码来计算一个字符串中的多个子字符串。我需要它以元组的形式返回结果。有什么建议吗Python 我需要这个子字符串计数程序来返回元组,python,list,tuples,Python,List,Tuples,我已经想出了这段代码来计算一个字符串中的多个子字符串。我需要它以元组的形式返回结果。有什么建议吗 def FindSubstringMatch(target, key): PositionList = 0 while PositionList < len(target): PositionList = target.find(key, PositionList) if PositionList == -1: break
def FindSubstringMatch(target, key):
PositionList = 0
while PositionList < len(target):
PositionList = target.find(key, PositionList)
if PositionList == -1:
break
print(PositionList)
PositionList += 2
FindSubstringMatch("atgacatgcacaagtatgcat", "atgc")
def FindSubstringMatch(目标,键):
PositionList=0
当位置列表def FindSubstringMatch(target, key):
PositionList = 0
result = []
while PositionList < len(target):
PositionList = target.find(key, PositionList)
if PositionList == -1:
break
result.append(PositionList)
PositionList += 2
return tuple(result)
无论哪种方式,它都能按预期工作:
findSubstringMatch("atgacatgcacaagtatgcat", "atgc")
=> (5, 15)
我鼓励您看看PEP 8并遵循python命名约定。我认为这部分是错误的:
PositionList+=2
为什么您同时跳过两个字符?对于某些输入,它会使函数失败,例如:findSubstringMatch(“attx”,“t”)
将返回(1,)
,但正确答案是(1,2)
。我在第二个回答中解决了这个问题。我想指出,正如您介绍的函数一样,它目前没有return
语句,因此它假定您打算在末尾编写returnnone
。要返回有用的内容,需要包含return
语句。
findSubstringMatch("atgacatgcacaagtatgcat", "atgc")
=> (5, 15)