Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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]
like image 877
jaap3 Avatar asked May 07 '12 13:05

jaap3


People also ask

How do you change the order of a sort in Python?

Python sorted() Function The sorted() function returns a sorted list of the specified iterable object. You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically. Note: You cannot sort a list that contains BOTH string values AND numeric values.

How do you sort a list in ascending order Python?

Python List sort() - Sorts Ascending or Descending List. The list. sort() method sorts the elements of a list in ascending or descending order using the default < comparisons operator between items. Use the key parameter to pass the function name to be used for comparison instead of the default < operator.

How do you order a list from least to greatest in Python?

key=len will tell the computer to sort the list of names by length from smallest to largest. reverse has a boolean value of True or False . In this example, reverse=True will tell the computer to sort the list in reverse alphabetical order.

How do you rearrange numbers in a list in Python?

Use the Python List sort() method to sort a list in place. The sort() method sorts the string elements in alphabetical order and sorts the numeric elements from smallest to largest. Use the sort(reverse=True) to reverse the default sort order.


1 Answers

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]
like image 175
HYRY Avatar answered Oct 17 '22 00:10

HYRY