我已经能够验证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()

其他回答

这是我在其他答案中没有看到的一个小智慧:

python中所有修改列表的可变对象(如列表)的方法都返回None。因此,对于列表,这也包括list.append(), list.reverse()等。这就是为什么语法应该是

myList.sort()

同时,任何不可变对象(比如字符串)的方法都必须这样赋值:

myString = myString.strip()

列表。Sort对列表进行排序,即它不会返回一个新的列表。只写

newList.sort()
return newList

问题就在这里:

answer = newList.sort()

Sort不会返回已排序的列表;相反,它对列表进行了适当的排序。

Use:

answer = sorted(newList)

如果想让它返回排序后的列表,可以使用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)

Python习惯地从改变数据的函数和方法中返回None,例如list。排序,列表。追加,随机。Shuffle,意思是它暗示了它正在变异的事实。

如果你想接受一个可迭代对象,并返回一个新的、已排序的可迭代对象项列表,请使用sorted内置函数。