为什么“return list.sort()”不返回列表而返回任何值?

2024-10-01 15:34:04 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: theanswerinfor排序lineitemlist
3条回答

list.sort对列表进行就地排序,即不返回新列表。就写吧

newList.sort()
return newList

问题在于:

answer = newList.sort()

sort不返回已排序的列表;而是对列表进行就地排序。

使用:

answer = sorted(newList)

Python的dev列表中的Guido van Rossum的Here is an email解释了为什么他选择不返回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()

相关问题 更多 >

    热门问题