python递归函数根本不返回任何内容

时间:2014-08-20 16:27:10

标签: python list function recursion return

我写了以下函数:

def splitter(input, inc=0):
    if inc == len(regex):
        print "return point reached"
        return input
    print inc, input
    output = []
    if type(input) is list:
        for i in input:
            o = re.split(regex[inc],i)
            if not o[0] == i:
                for x in o:
                    output.append(x)
            else:
                output.append(i)
    else:
        o = re.split(regex[inc],input)
        if not o[0] == input:
            for x in o:
                output.append(x)
        else:
            output.append(input)
    inc+=1
    splitter(output, inc)

正则表达式定义为:

regex = [' & ',' / ',' \+ ',' and ',' und ',' ft\. ',' feat\. ']

输入是一些字符串,如

"Benga und Welsh ft. Warrior Queen and Skream feat. Benny Ill"

目标是在正则表达式中的条目指定的每个点处拆分字符串。 由print inc, input行打印的输出执行预期的操作(它为输入提供['Benga', 'Welsh', 'Warrior Queen', 'Skream feat. Benny Ill']),即使正在执行print "return point reached"的行,但函数似乎没有什么都归还。 知道我从django manage.py-shell调用函数是否很重要?

感谢任何有用的想法! [R

1 个答案:

答案 0 :(得分:1)

您在函数的最后一行缺少return。以下是工作代码的示例,其中缩进已修复:

import re

regex = [' & ',' / ',' \+ ',' and ',' und ',' ft\. ',' feat\. ']

def splitter(input, inc=0):
    if inc == len(regex):
        print "return point reached"
        return input
    print inc, input
    output = []
    if type(input) is list:
        for i in input:
            o = re.split(regex[inc], i)
            if not o[0] == i:
                for x in o:
                    output.append(x)
            else:
                output.append(i)
    else:
        o = re.split(regex[inc], input)
        if not o[0] == input:
            for x in o:
                output.append(x)
        else:
            output.append(input)
    inc += 1

    # I added the return statement here:
    return splitter(output, inc)

print(splitter("Benga und Welsh ft. Warrior Queen and Skream feat. Benny Ill"))

输出:

0 Benga und Welsh ft. Warrior Queen and Skream feat. Benny Ill
1 ['Benga und Welsh ft. Warrior Queen and Skream feat. Benny Ill']
2 ['Benga und Welsh ft. Warrior Queen and Skream feat. Benny Ill']
3 ['Benga und Welsh ft. Warrior Queen and Skream feat. Benny Ill']
4 ['Benga und Welsh ft. Warrior Queen', 'Skream feat. Benny Ill']
5 ['Benga', 'Welsh ft. Warrior Queen', 'Skream feat. Benny Ill']
6 ['Benga', 'Welsh', 'Warrior Queen', 'Skream feat. Benny Ill']
return point reached
['Benga', 'Welsh', 'Warrior Queen', 'Skream', 'Benny Ill']