【发布时间】:2023-01-30 03:43:04
【问题描述】:
我已经能够验证 findUniqueWords 确实会导致排序的 list。但是,它不返回列表。为什么?
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)
answer = newList.sort()
return answer
【问题讨论】:
-
我认为您不需要多次将 item 转换为字符串。通常一次就足够了,而且在 cleanUp 的输入上执行它也更干净。
-
只是一个愚蠢的想法,但如果你想要一个独特项目的列表,你为什么不转换成一个集合呢?然后,您可以根据需要将它们转换回列表。
theSet= set(theList)大功告成,只需要将其转换回列表即可:theList = list(theSet)大功告成。简单的。 -
添加@runlevel0 所说的(这是一个好主意):您可以转换
theSet' into a sorted list withsorted(theSet)`。 -
非常不规则的语言
-
仅仅因为链接在一种语言中是一种常见的 API 习语并不意味着它必须在所有语言中都存在,并且它与函数式编程关系不大(函数式编程鼓励使用不可变值,这使得变异方法返回的问题对对象的引用)。
标签: python list sorting return