简体   繁体   中英

What's wrong with my Python code? I'm trying to deep-reverse a list input

def is_list(p):

    return isinstance(p, list)


def deep_reverse(list):

    o=[]
    for i in reversed(list):

        if is_list(i)==True:
            print i
            deep_reverse(i)

        o.append(i)

    return o

For example:

p = [1, [2, 3, [4, [5, 6]]]]
print deep_reverse(p)
#>>> [[[[6, 5], 4], 3, 2], 1]

Change the line

        deep_reverse(i)

to

        i = deep_reverse(i)

Incidentally, a shorter way to write this function would be:

def deep_reverse(lst):
    if not is_list(lst):
        return lst
    return map(deep_reverse, reversed(lst))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM