[英]How to order strings with numbers and letters in order to categorize in python?
[英]How to sort strings with letters and numbers in python by a specific order
我有一個列表,希望按特定順序進行排序。 我已經嘗試了來自stackoverflow的各種方法,但它們並沒有為我提供所需的答案。 任何幫助,將不勝感激
order_list = ['ABC123'] #this is the list that should define the order, according to the first character
lst = ['AA2', 'A3', 'A1', 'AA1', 'BBB2', 'A2', 'AA3', 'BBB1', 'AAA', 'BBB3']
print(sort_method(lst))
>>>['AAA', 'AA1', 'AA2', 'AA3', 'A1', 'A2', 'A3', 'BBB1', 'BBB2', 'BBB3','CCC1','CCC2']
#different orderlist
order_list = ['CBA123']
lst = ['BBB3', 'AA2', 'A2', 'BBB2', 'CCC2', 'AA3', 'CCC1', 'AAA', 'AA1', 'A3', 'BBB1', 'A1']
print(sort_method(lst))
>>>['CCC1','CCC2','BBB1', 'BBB2', 'BBB3','AAA', 'AA1', 'AA2', 'AA3', 'A1', 'A2', 'A3']
無需在此處定義您自己的函數。 sorted
的stdlib函數采用一個命名參數,該key
可用於指定排序順序。 嘗試這個:
print( sorted( lst, key=lambda x:[order_list[0].index(y) for y in x] ))
key
函數將基於要排序的字符串中每個字符在order_list
的位置獲取索引列表。
如果lst
中存在不存在於order_list
任何字符,則將引發異常。
您還可以使用dict
來保持排序順序:
someorder = {letter: val for val, letter in enumerate(order_list[0])}
# then use get on the dictionary for fast lookup
print(sorted(lst, key = lambda x: [someorder.get(letter) for letter in x]))
# ['AAA', 'AA1', 'AA2', 'AA3', 'A1', 'A2', 'A3', 'BBB1', 'BBB2', 'BBB3']
在哪里, get
還將允許您為找不到的任何字符設置默認值:
default_value = max(someorder.values())+1
print(sorted(['A', 'BBB', 'X'], key = lambda x: [someorder.get(letter, default_value) for letter in x]))
# ['A', 'BBB', 'X']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.