Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我需要这个子字符串计数程序来返回元组_Python_List_Tuples - Fatal编程技术网

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 当位置列表 这段代码打印: 5. 十五

我希望它能返回: (5,15)

试试这个:

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)