Python reorder a sorted list so the highest value is in the middle

我的未来我决定 提交于 2021-02-20 09:20:40

问题


I need to reorder a sorted list so the "middle" element is the highest number. The numbers leading up to the middle are incremental, the numbers past the middle are in decreasing order.

I have the following working solution, but have a feeling that it can be done simpler:

foo = range(7)
bar = [n for i, n in enumerate(foo) if n % 2 == len(foo) % 2]
bar += [n for n in reversed(foo) if n not in bar]
bar
[1, 3, 5, 6, 4, 2, 0]

回答1:


how about:

foo[len(foo)%2::2] + foo[::-2]

In [1]: foo = range(7)
In [2]: foo[len(foo)%2::2] + foo[::-2]
Out[2]: [1, 3, 5, 6, 4, 2, 0]
In [3]: foo = range(8)
In [4]: foo[len(foo)%2::2] + foo[::-2]
Out[4]: [0, 2, 4, 6, 7, 5, 3, 1]



回答2:


Use slicing with a step of 2 going up, and -2 going back:

>>> foo[1::2]+foo[-1::-2]
[1, 3, 5, 6, 4, 2, 0]


来源:https://stackoverflow.com/questions/10482684/python-reorder-a-sorted-list-so-the-highest-value-is-in-the-middle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!