Python organizes the sorted list, so the largest value is in the middle

I need to reorder the sorted list so that the “middle” item is the highest number. The numbers leading to the middle are incremental, the numbers beyond the middle are in descending order.

I have the following working solution, but I have a feeling that this can be done easier:

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]
+3
source share
2 answers

What 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]
+6
source

Use slice in increments of 2, up and -2:

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

All Articles