Python 重新排序已排序的列表,以便最大值位于中间 [英] Python reorder a sorted list so the highest value is in the middle

查看:74
本文介绍了Python 重新排序已排序的列表,以便最大值位于中间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要重新排序一个排序列表,以便中间"元素是最高的数字.到中间的数字是递增的,经过中间的数字是递减的.

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]

推荐答案

怎么样:

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]

这篇关于Python 重新排序已排序的列表,以便最大值位于中间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆