【发布时间】:2011-11-10 04:41:09
【问题描述】:
我已经能够验证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