问题描述:

everyone!

I am a beginner in python programming. I am writing a python program to reverse a given input list. Following is the code for it:

 L1=list(input("Enter the numbers of list to be reversed : "))

L2=[]

def rever(La,Lb):

if len(Lb)==0:

return La

else:

return rever(La.append(Lb.pop(0)),Lb)

print rever(L2,L1)

For example, if we input,

 1,2,3

The output should be,

 [3,2,1]

But this is not happening. Python is giving the following error:

 Traceback (most recent call last):

File "Q3.py", line 10, in <module>

print rever(L2,L1)

File "Q3.py", line 8, in rever

return rever(La.append(Lb.pop(0)),Lb)

File "Q3.py", line 8, in rever

return rever(La.append(Lb.pop(0)),Lb)

AttributeError: 'NoneType' object has no attribute 'append'

I don't get it. Please help me out!!

网友答案:

may be you should look at this, instead of pop and append

In [5]: L1=list(input("Enter the numbers of list to be reversed : "))
Enter the numbers of list to be reversed : 1,2,3,4,5

In [6]: L1
Out[6]: [1, 2, 3, 4, 5]

In [7]: L2 = L1[::-1]

In [8]: L2
Out[8]: [5, 4, 3, 2, 1]
网友答案:

There are a couple issues. First the working way:

def rever(La,Lb):
    if len(Lb)==0: 
        return La
    else:
        La.append(Lb.pop())
        return rever(La,Lb)

list.append appends in place, meaning it returns None. Since you are passing La.append as an argument in the recursion, you get an error on the second iteration.

If you wanted to do it that way then you could do

return rever(La + [Lb.pop()], Lb)

The second issue is you are popping off the front and appending. So you will get the same order. Instead, pop off the end (no argument to pop) and append.

网友答案:

The append method operates in-place, altering the original list and returning None, giving you the error. Try this instead:

def rever(La, Lb):
    if len(Lb) == 0:
        return La
    else:
        La.append(Lb.pop())
        return rever(La, Lb)

You could also refactor your code to something like this:

def rever(La, Lb):
    if Lb:
        La.append(Lb.pop())
        return rever(La, Lb)
    return La

This uses the facts that an empty list is False in a boolean context, and there can only be one return value for any function.

相关阅读:
Top