Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.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_Python 3.x_String_List_Python 2.7 - Fatal编程技术网

Python 如何使用递归提取子字符串列表?

Python 如何使用递归提取子字符串列表?,python,python-3.x,string,list,python-2.7,Python,Python 3.x,String,List,Python 2.7,给一个字符串,比如说, strr=“int a;int b;int c;” 如何从这个字符串中提取包含类似['int a'、'int b'、'int c']的元素的列表。 我想用递归实现这个输出,而不使用正则表达式。请指导。虽然有更简单的方法,但使用递归的解决方案如下 def extract(s): ' finds substrings delimited by ; ' try: index = s.index(';') # current wor

给一个字符串,比如说,
strr=“int a;int b;int c;”
如何从这个字符串中提取包含类似
['int a'、'int b'、'int c']
的元素的列表。
我想用递归实现这个输出,而不使用正则表达式。请指导。

虽然有更简单的方法,但使用递归的解决方案如下

def extract(s):
    ' finds substrings delimited by ; '
    try:
        index = s.index(';')
        # current word + recursion for remainder
        # index + 1 in recursion to skip over ';'
        return [s[:index]] + extract(s[index+1:])
    except:
        # delimiter wasn't found (base case)
        return []
用法


您可以使用内置的
split
和'strip'功能:

l = strr.split(';')
l = [x.strip() for x in l]
l.remove('')
输出:

['int a', 'int b', 'int c']

但是为什么要递归呢?您可以只使用
strr.split(“;”)
['int a', 'int b', 'int c']