问题
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