理解清單排序的回傳值
在Python中,在清單上使用「sort()」函數並不會直接傳回排序後的列表。相反,它會就地修改原始列表,而不產生明確回傳值。
這種與期望的偏差可能會導致混亂,因為呼叫者可能會期望函數傳回排序後的清單。澄清一下,「list.sort()」不會建立新的排序列表,而是重新組織現有列表中的元素。
要取得所需的排序清單作為輸出,程式碼應明確傳回排序清單。所提供的程式碼片段的更正版本應為:
def findUniqueWords(theList): newList = [] words = [] # Read a line at a time for item in theList: # Remove any punctuation from the line cleaned = cleanUp(item) # Split the line into separate words words = cleaned.split() # Evaluate each word for word in words: # Count each unique word if word not in newList: newList.append(word) newList.sort() return newList
透過在循環外部添加“newList.sort()”,列表將就地排序。然後,傳回「newList」確保排序後的清單可供呼叫者使用。
以上是為什麼 Python 的 `list.sort()` 不傳回排序清單?的詳細內容。更多資訊請關注PHP中文網其他相關文章!