2017-08-13 59 views
3

當給出['mix', 'xyz', 'apple', 'xanadu', 'aardvark']列表時,代碼不返回最後一個字。需要對給定的字符串進行排序(字符串以x開頭)

def front_x(words): 
    x_list = [] 
    no_x_list = [] 
    [x_list.append(i) for i in words if i[0] == "x"] 
    [no_x_list.append(words[i2]) for i2 in range(len(words)-1) if words[i2] not in x_list] 
    x_list.sort() 
    no_x_list.sort() 
    return x_list + no_x_list 
print front_x(['mix', 'xyz', 'apple', 'xanadu', 'aardvark']) 

必須是:

['xanadu', 'xyz', 'aardvark', 'apple', 'mix'] 

隨着名單['bbb', 'ccc', 'axx', 'xzz', 'xaa']['ccc', 'bbb', 'aaa', 'xcc', 'xaa']一切是正確的['xaa', 'xzz', 'axx', 'bbb', 'ccc']['xaa', 'xcc', 'aaa', 'bbb', 'ccc']

回答

3

range(len(words)-1)的迭代看起來不正確。更多的是,使列表附加列表理解是相當unpythonic; list comps是用於建立不使列表附加的列表,而這是諷刺這裏。

您可以通過基於二元組進行排序來進行一次排序,該二元組的第一項檢查單詞'x'開頭並將其放在前面。在數組中的第二項施加lexicograhical排序名單上,打破關係:

def front_x(words): 
    return sorted(words, key=lambda y: (not y.startswith('x'), y)) 

print front_x(['mix', 'xyz', 'apple', 'xanadu', 'aardvark']) 
# ['xanadu', 'xyz', 'aardvark', 'apple', 'mix'] 
1

你可以試試這個:

words = ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] 

new_words = [i for i in words if i[0].lower() == "x"] 

words = [i for i in words if i[0].lower() != "x"] 

final_words = sorted(new_words)+sorted(words) 

print(final_words) 

輸出:

['xanadu', 'xyz', 'aardvark', 'apple', 'mix'] 
2

只需卸下-1從range(len(words)-1) 這將是你的代碼的最小變化。

1

您必須使用len(words)而不是len(words)-1才能獲得預期的輸出。

所以,試試這個方法:

def front_x(words): 
    x_list = [] 
    no_x_list = [] 
    [x_list.append(i) for i in words if i[0] == "x"] 
    [no_x_list.append(words[i2]) for i2 in range(len(words)) if words[i2] not in x_list] 
    x_list.sort() 
    no_x_list.sort() 
    return x_list + no_x_list 

print front_x(['mix', 'xyz', 'apple', 'xanadu', 'aardvark']) 

輸出:

['xanadu', 'xyz', 'aardvark', 'apple', 'mix'] 
+0

這是一個簡單的重複回答 – Cuber

+0

@Cuber,如何???? –

+0

應該是一個編輯 –

相關問題