My problem, I would like to sort the below list (using Python)
my_list = ['2', '1', '1+', '1-', '2+', '2-']
into
my_list = ['1+', '1', '1-', '2+', '2', '2-']
Edit:
I tried sorted
which gives me ['1', '1+', '1-', '2', '2+', '2-']
Therefore, the order of '1' and '1+' should be changed, or '2+' and '2', etc. for all other numbers as well.
Arbitrary rules call for an arbitrary expendable solution: I am relying on the fact that tuples sort element by element, so the numbers 0
, 1
, 2
serve as priorities:
def plus_before_minus(item):
number = item.rstrip('+-')
if item.endswith('+'):
return (number, 0)
elif item.endswith('-'):
return (number, 2)
else:
return (number, 1)
with that, the list sorts as required:
>>> sorted(my_list, key=plus_before_minus)
['1+', '1', '1-', '2+', '2', '2-']
Here, I am firstly creating a function get_priority
to return the priority of each element. This returned number will be later used for sorting.
def get_priority(x):
return {
'+': 1,
'-': 3
}.get(x, 2)
# If returned number:
# ends with '-': return 3 (Highest / First)
# ends with '+': return 1 (Lowest / Last)
# else: return 2 (Medium / Middle)
Then here I am going to use get_priority
function along with itertools.groupby()
, operator.itemgetter()
and sorted()
to achieve your desired order as:
from itertools import groupby
from operator import itemgetter
my_list = ['2', '1', '1+', '1-', '2+', '2-']
new_list = [i for _, l in groupby(sorted(my_list), key=itemgetter(0)) for i in sorted(l, key= lambda x: get_priority(x[-1]))]
where new_list
will return you the value:
['1+', '1', '1-', '2+', '2', '2-']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.