我已经能够验证findUniqueWords确实会导致一个排序的列表。但是,它不返回列表。为什么?
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
要理解为什么它不返回列表:
Sort()方法不返回任何值,而Sort()方法只是按特定顺序对给定列表中的元素进行排序——升序或降序,而不返回任何值。
所以问题是answer = newList.sort(),其中答案为none。
相反,你可以只返回newList.sort()。
sort()方法的语法是:
list.sort(key=..., reverse=...)
或者,你也可以使用Python的内置函数sorted()来达到同样的目的。
sorted(list, key=..., reverse=...)
注意:sort()和sorted()之间最简单的区别是:sort()不返回任何值,而sorted()返回一个可迭代列表。
在这里,answer = sorted(newList)
下面是Guido van Rossum在Python开发列表中的一封电子邮件,解释了为什么他选择在影响对象的操作上不返回self,并且不返回新操作。
This comes from a coding style (popular in various other languages, I
believe especially Lisp revels in it) where a series of side effects
on a single object can be chained like this:
x.compress().chop(y).sort(z)
which would be the same as
x.compress()
x.chop(y)
x.sort(z)
I find the chaining form a threat to readability; it requires that the
reader must be intimately familiar with each of the methods. The
second form makes it clear that each of these calls acts on the same
object, and so even if you don't know the class and its methods very
well, you can understand that the second and third call are applied to
x (and that all calls are made for their side-effects), and not to
something else.
I'd like to reserve chaining for operations that return new values,
like string processing operations:
y = x.rstrip("\n").split(":").lower()