6

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]
jaap3
  • 2,696
  • 19
  • 34
  • What is the use case for this? – Daenyth May 07 '12 at 13:11
  • The list will be displayed horizontal (and won't contain numbers). Visually it makes sense to put the "highest" number in the middle and descent outwards form there... – jaap3 May 07 '12 at 13:15

2 Answers2

10

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]
HYRY
  • 94,853
  • 25
  • 187
  • 187
  • That's pretty cool and works perfectly for my use case. I always forget about the extended slice syntax – jaap3 May 07 '12 at 13:42
1

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]
PaulMcG
  • 62,419
  • 16
  • 94
  • 130