简体   繁体   中英

Unexpected result reversing Python array

When I write this code:

f=['a','b','c',['d','e','f']]
def j(f):
    p=f[:]
    for i in range(len(f)):
        if type(p[i]) == list:
            p[i].reverse()
    p.reverse()
    return p
print(j(f), f)

I expect that the result would be:

[['f', 'e', 'd'], 'c', 'b', 'a'] ['a', 'b', 'c', ['d', 'e', 'f']]

But the result I see is:

[['f', 'e', 'd'], 'c', 'b', 'a'] ['a', 'b', 'c', ['f', 'e', 'd']]

Why? And how can I write a code that do what I expect?

reverse modifies the list in place, you actually want to create a new list, so you don't reverse the one you've got, something like this:

def j(f):
    p=f[:]
    for i in range(len(f)):
        if type(p[i]) == list:
            p[i] = p[i][::-1]
    p.reverse()
    return p

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