[已解決]python sort()函式返回None
阿新 • • 發佈:2021-01-24
背景:
最近在跟著coursera上面Dr.Chuck課程《Python Data Structures》入門python,遇到關於list結構使用sort函式排序的一點問題。
(btw:Dr.Chuck真的不要太有魅力啊,感覺自己本來對程式設計無感的的弱雞都開始喜歡上了。向想學習的小夥伴牆裂推薦Dr.Chuck的一系列課程。
課程傳送門
問題描述:
程式碼如下所示,在使用sort函式後,本來應該對list排序卻顯示None
fname = input("please enter the file path:") fh = open(fname) lst = list() for line in fh: for i in line.split(): if i in lst: continue lst.append(i) print(lst.sort())
結果顯示:None
原因分析:
網上衝浪了一波後發現,list.sort()後是雖然在列表內部進行了排序, 但這波操作後不會有返回值, 所以此處顯示為None。
但是其實在python IDLE中是能夠成功返回的:
解決方案:
其實非常簡單,只用將sort函式改成sorted()就可以正常顯示啦!
希望能對大家有所幫助~
print(sorted(lst))