[英]Python - sort strings / numeric
我的問題,我想對下面的列表進行排序(使用 Python)
my_list = ['2', '1', '1+', '1-', '2+', '2-']
進入
my_list = ['1+', '1', '1-', '2+', '2', '2-']
編輯:
我試過sorted
這給了我['1', '1+', '1-', '2', '2+', '2-']
因此,“1”和“1+”的順序應該改變,或者“2+”和“2”等所有其他數字的順序也應該改變。
任意規則需要任意可消耗的解決方案:我依賴於元組按元素排序的事實,因此數字0
、 1
、 2
用作優先級:
def plus_before_minus(item):
number = item.rstrip('+-')
if item.endswith('+'):
return (number, 0)
elif item.endswith('-'):
return (number, 2)
else:
return (number, 1)
這樣,列表將根據需要進行排序:
>>> sorted(my_list, key=plus_before_minus)
['1+', '1', '1-', '2+', '2', '2-']
在這里,我首先創建一個 function get_priority
來返回每個元素的優先級。 這個返回的數字稍后將用於排序。
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)
然后在這里我將使用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]))]
new_list
將返回您的值:
['1+', '1', '1-', '2+', '2', '2-']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.