简体   繁体   中英

Swap and reverse elements in a python list

I have a list with elements as following:

L =[1, 2, 3, 4, 5]

I want to mirror and reorder as follows:

L =[1,5,2,4,3]

Numbers and size of elements in the list may vary and change!

Having some other examples,

K=[1, 2, 3]

Output may come out as:

K=[1, 3, 2]

And

D=[1,2,3,4]

Final results:

D = [1,4,2,3]

I have tried to do it with slice, it doesn't work for me.

You can do that by merging the list with its reverse:

lst = [1,2,3,4,5]

b = [c for a,b in zip(lst,reversed(lst)) for c in (a,b)][:len(lst)]

print(b) # [1, 5, 2, 4, 3]

Is this what you're looking for?

from random import shuffle

my_list = [1,2,3,4,5]
print (my_list)
shuffle (my_list)
print (my_list)

The following code gives you the expected output.

l = [1,2,3,4,5]

r = []
for i in range(len(l)):
    if i % 2 == 0:
        r.append(l[i // 2])
    else:
        r.append(l[-1 - i // 2])

print(r)  # prints [1, 5, 2, 4, 3]

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