鑒于我在 Python 中有一個字串串列:
list = [" banana ", "Cherry", "apple"]
我想將此串列排序為不區分大小寫并忽略空格。所以像這樣:
list = ["apple", " banana ", "Cherry"]
如果我使用這個:
sorted(list, key=str.casefold)
我明白了:
list = [" banana ", "apple", "Cherry"]
它不區分大小寫,但空格字符位于字母之前。
如果我使用這個:
sorted(list, key=lambda x:x.replace(' ', ''))
我明白了:
list = ["Cherry", "apple", " banana "]
它忽略空格但不區分大小寫。我試圖將這兩種解決方案結合起來,但我無法使其發揮作用。有沒有辦法輕松解決這個問題并“合并”這兩個結果?
uj5u.com熱心網友回復:
您可以str.strip()用于從字串的開頭和結尾洗掉空格并str.casefold()用于不區分大小寫的排序。
lst = [" banana ", "Cherry", "apple"]
res = sorted(lst, key=lambda x: x.strip().casefold())
print(res)
輸出:
['apple', ' banana ', 'Cherry']
uj5u.com熱心網友回復:
只需鏈接電話
values = [" banana ", "Cherry", "apple"]
print(sorted(values, key=lambda x: x.replace(' ', '').casefold()))
# ['apple', ' banana ', 'Cherry']
只丟棄開頭和結尾的空格,我建議str.strip
print(sorted(values, key=lambda x: x.strip().casefold()))
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/535652.html
標籤:Python细绳列表排序
