我已经能够验证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
下面是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()
如果想让它返回排序后的列表,可以使用sorted()方法。
这样更方便。
l1 = []
n = int(input())
for i in range(n):
user = int(input())
l1.append(user)
sorted(l1,reverse=True)
list.sort()方法就地修改列表并返回None。
如果你还想使用排序,你可以这样做。
l1 = []
n = int(input())
for i in range(n):
user = int(input())
l1.append(user)
l1.sort(reverse=True)
print(l1)