从列表中返回一个字符串

时间:2016-03-08 18:17:41

标签: python

我有代码尝试使用Python从列表中反转字符串,并且不能使用传统方法作为练习的一部分(我不能在迭代时改变列表,我必须递归地执行)但我的函数不会返回我的字符串,不确定问题是什么:

list1 = []

def reverse(text):
    note = ''
    for x in text:
        list1.append(x)
    print list1

#    for x in list1:
#        note = note+list1.pop()

    def recursive(toRev):
        if not list1:
                print toRev, 'Last toRev'
                return toRev

        else:
                toRev = toRev+list1.pop()
                recursive(toRev)
        print toRev, 'Note with in the loop'

        #recursive(toRev)


    finalvar = recursive(note)
    print finalvar, ' :Final'
    return finalvar

reverse('Python!')

3 个答案:

答案 0 :(得分:0)

你没有对递归调用的结果做任何事情,也没有将它传递给链。 尝试将recursive更改为:

def recursive(toRev):
    if not list1:
        print toRev, 'Last toRev'
        return toRev
    else:
        toRev = toRev+list1.pop()
        print toRev, 'Note with in the loop'
        return recursive(toRev)

答案 1 :(得分:0)

您似乎错过了return函数中的recursive。您还应该在函数内定义list1,而不是在函数外部。

def reverse(text):
    list1 = [] # defined inside of function
    note = ''
    for x in text:
        list1.append(x)
    #print list1

#    for x in list1:
#        note = note+list1.pop()

    def recursive(toRev):
        if not list1:
               #print toRev, 'Last toRev'
                return toRev

        else:
                toRev = toRev+list1.pop()
                return recursive(toRev) # added return
        #print toRev, 'Note with in the loop'

        #recursive(toRev)


    finalvar = recursive(note)
    #print finalvar, ' :Final'
    return finalvar

reverse('Python!')

答案 2 :(得分:0)

感谢StephenTG

list1 = []

    def reverse(text):
        note = ''
        for x in text:
            list1.append(x)
        print list1

    #    for x in list1:
    #        note = note+list1.pop()

        def recursive(toRev):
            if not list1:
                    print toRev, 'Last toRev'
                    return toRev

            else:
                    toRev = toRev+list1.pop()
                    return recursive(toRev)
                    #return toRev
            print toRev, 'Note with in the loop'

            #recursive(toRev)


        finalvar = recursive(note)
        print finalvar, ' :Final'
        return finalvar

    reverse('Python!')