(你已經改變了你的問題想用字符串,而不是與對象做到這一點,所以這個例子是字符串。)
使用每個字符串的索引列表謂詞提供key
依據其進行排序您定列表:
>>> wanted_order = ['BODY.H', 'BODY.M', 'BODY.VL', 'WHL0.H']
>>> got_list = ['WHL0.H', 'BODY.H', 'BODY.VL', 'BODY.VL', 'WHL0.H', 'BODY.M']
>>> sorted(got_list, key=lambda s: wanted_order.index)
['BODY.H', 'BODY.M', 'BODY.VL', 'BODY.VL', 'WHL0.H', 'WHL0.H']
請注意,我在got_list
添加了一些額外的重複項目,以顯示它如何會使用通用輸入和多個每個。
順便說一句,如果總是隻有這4個對象,爲什麼不用這4個創建一個列表呢?
另外,如果從謂詞中缺少一個字符串,則會出現錯誤。所以也許把它放在一個函數(而不是lambda)中,如果發生錯誤,並且返回另一個值。
編輯:
對於你願意,你可以使用s.name
密鑰和謂語什麼對象版本(當然,wanted_order
有對象的名稱):
>>> sorted(got_list, key=lambda s: wanted_order.index(s.name))
編輯2:
要處理got_list
中沒有「姓名」的項目wanted_order
:
>>> def predicated_key(item):
... wanted_order = ['BODY.H', 'BODY.M', 'BODY.VL', 'WHL0.H']
... # put wanted_order in global scope if you prefer instead of here
... try:
... return wanted_order.index(item) # or item.name in your case
... except ValueError:
... return len(wanted_order) # since this will be higher than the
... # index of the any item on the list
...
>>> got_list = ['WHL0.H', 'BODY.H', 'something', 'BODY.VL',
... 'something else', 'BODY.VL', 'WHL0.H', 'BODY.M']
>>> sorted(got_list, key=predicated_key)
['BODY.H', 'BODY.M', 'BODY.VL', 'BODY.VL', 'WHL0.H', 'WHL0.H', 'something', 'something else']
這是沒有足夠的信息,它可能是很好的包括您使用的代碼與實際結果和所需的行爲。另請參見[如何創建最小,完整和可驗證的示例](http://stackoverflow.com/help/mcve) –
問題是我不知道從哪裏開始。 – aaro4130
沒有人能夠幫助你,除非你更清楚地解釋你的問題... –