[英]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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.