[英]How to sort the list in the specific ordering
我正在研究加擾排序功能,它需要兩個參數:
它返回根據第二個參數排序的字符串列表。
例如:
scramble(['abc', 'bac', 'abb'], 'cba')
應該回來
['bac', 'abc', 'abb']
此調用中的第二個參數用於比較目的,c < b < a。 因此,以“b”開頭的單詞排在以“a”開頭的單詞之前; 並且 'abc' 出現在 'abb' 之前,因為不考慮公共前綴('ab'),'c' 出現在 'b' 之前。
def scramble(l : [str], ordering : str) -> [str]:
for i in ordering:
for h in l:
l.sort(key = h.index(i))
break
return l
我的代碼不起作用,我只得到了按列表中項目的字母索引(根據排序)對列表進行排序的一般想法。 有人可以幫我修復我的代碼嗎?
def scramble(words, order):
return sorted(words, key = lambda word: [order.index(char) for char in word])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.