简体   繁体   English

Python - 排序字符串/数字

[英]Python - sort strings / numeric

My problem, I would like to sort the below list (using Python)我的问题,我想对下面的列表进行排序(使用 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-']我试过sorted这给了我['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.因此,“1”和“1+”的顺序应该改变,或者“2+”和“2”等所有其他数字的顺序也应该改变。

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:任意规则需要任意可消耗的解决方案:我依赖于元组按元素排序的事实,因此数字012用作优先级:

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.在这里,我首先创建一个 function get_priority来返回每个元素的优先级。 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:然后在这里我将使用get_priority function 以及itertools.groupby()operator.itemgetter()sorted()来实现您想要的顺序:

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: new_list将返回您的值:

['1+', '1', '1-', '2+', '2', '2-']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM