为什么“ return list.sort()”返回None,而不返回列表?

问题:为什么“ return list.sort()”返回None,而不返回列表?

我已经能够验证findUniqueWords结果是否为sorted 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

I’ve been able to verify that the findUniqueWords does result in a sorted list. However, it does not return the list. Why?

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

回答 0

list.sort对列表进行适当排序,即不返回新列表。写就好了

newList.sort()
return newList

list.sort sorts the list in place, i.e. it doesn’t return a new list. Just write

newList.sort()
return newList

回答 1

问题在这里:

answer = newList.sort()

sort不返回排序列表;而是将列表排序到位。

用:

answer = sorted(newList)

The problem is here:

answer = newList.sort()

sort does not return the sorted list; rather, it sorts the list in place.

Use:

answer = sorted(newList)

回答 2

这是 Guido van Rossum在Python开发清单中的一封电子邮件,解释了为什么他选择不返回self影响该对象的操作并且不返回新对象的原因。

这来自一种编码样式(在各种其他语言中很流行,我相信尤其是Lisp令人反感),其中可以将单个对象上的一系列副作用链接成这样:

 x.compress().chop(y).sort(z)

这将与

  x.compress()
  x.chop(y)
  x.sort(z)

我发现链接对可读性构成威胁;它要求读者必须对每种方法都非常熟悉。第二种形式清楚地表明,每个调用都作用于同一对象,因此,即使您不太了解类及其方法,您也可以理解第二种和第三种调用都适用于x(并且所有呼叫都是出于副作用),而不是其他。

我想为返回新值的操作保留链接,例如字符串处理操作:

 y = x.rstrip("\n").split(":").lower()

Here is an email from Guido van Rossum in Python’s dev list explaining why he choose not to return self on operations that affects the object and don’t return a new one.

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()

回答 3

蟒习惯性地返回None从功能和变异的数据的方法,例如list.sortlist.appendrandom.shuffle,与想法是,它暗示一个事实,即它是变异。

如果要进行迭代并返回其项目的新排序列表,请使用sorted内置函数。

Python habitually returns None from functions and methods that mutate the data, such as list.sort, list.append, and random.shuffle, with the idea being that it hints to the fact that it was mutating.

If you want to take an iterable and return a new, sorted list of its items, use the sorted builtin function.


回答 4

Python有两种排序方式:sort 方法(或“成员函数”)和sort 函数。sort方法对命名对象的内容进行操作-将其视为对象要对其自身重新排序的操作。排序功能是对由对象表示的数据进行的操作,并按排序顺序返回内容相同的新对象。

给定一个名为l的整数列表,如果我们调用,则列表本身将重新排序l.sort()

>>> l = [1, 5, 2341, 467, 213, 123]
>>> l.sort()
>>> l
[1, 5, 123, 213, 467, 2341]

此方法没有返回值。但是,如果我们尝试分配的结果l.sort()呢?

>>> l = [1, 5, 2341, 467, 213, 123]
>>> r = l.sort()
>>> print(r)
None

r现在实际上等于什么。这是程序员在离开Python一段时间后很可能会忘记的那些怪异的,有些令人讨厌的细节(这就是为什么我要编写这个东西,所以不会再忘记了)。

sorted()另一方面,该函数不会对的内容做任何事情l,但会返回一个新的,排序后的列表,其内容与以下内容相同l

>>> l = [1, 5, 2341, 467, 213, 123]
>>> r = sorted(l)
>>> l
[1, 5, 2341, 467, 213, 123]
>>> r
[1, 5, 123, 213, 467, 2341]

请注意,返回的值是不是一个深拷贝,所以要谨慎了包含列表照常中的元素侧effecty操作:

>>> spam = [8, 2, 4, 7]
>>> eggs = [3, 1, 4, 5]
>>> l = [spam, eggs]
>>> r = sorted(l)
>>> l
[[8, 2, 4, 7], [3, 1, 4, 5]]
>>> r
[[3, 1, 4, 5], [8, 2, 4, 7]]
>>> spam.sort()
>>> eggs.sort()
>>> l
[[2, 4, 7, 8], [1, 3, 4, 5]]
>>> r
[[1, 3, 4, 5], [2, 4, 7, 8]]

Python has two kinds of sorts: a sort method (or “member function”) and a sort function. The sort method operates on the contents of the object named — think of it as an action that the object is taking to re-order itself. The sort function is an operation over the data represented by an object and returns a new object with the same contents in a sorted order.

Given a list of integers named l the list itself will be reordered if we call l.sort():

>>> l = [1, 5, 2341, 467, 213, 123]
>>> l.sort()
>>> l
[1, 5, 123, 213, 467, 2341]

This method has no return value. But what if we try to assign the result of l.sort()?

>>> l = [1, 5, 2341, 467, 213, 123]
>>> r = l.sort()
>>> print(r)
None

r now equals actually nothing. This is one of those weird, somewhat annoying details that a programmer is likely to forget about after a period of absence from Python (which is why I am writing this, so I don’t forget again).

The function sorted(), on the other hand, will not do anything to the contents of l, but will return a new, sorted list with the same contents as l:

>>> l = [1, 5, 2341, 467, 213, 123]
>>> r = sorted(l)
>>> l
[1, 5, 2341, 467, 213, 123]
>>> r
[1, 5, 123, 213, 467, 2341]

Be aware that the returned value is not a deep copy, so be cautious about side-effecty operations over elements contained within the list as usual:

>>> spam = [8, 2, 4, 7]
>>> eggs = [3, 1, 4, 5]
>>> l = [spam, eggs]
>>> r = sorted(l)
>>> l
[[8, 2, 4, 7], [3, 1, 4, 5]]
>>> r
[[3, 1, 4, 5], [8, 2, 4, 7]]
>>> spam.sort()
>>> eggs.sort()
>>> l
[[2, 4, 7, 8], [1, 3, 4, 5]]
>>> r
[[1, 3, 4, 5], [2, 4, 7, 8]]

回答 5

要了解为什么它不返回列表:

sort()不返回任何值,而sort()方法仅以特定顺序对给定列表的元素进行排序- 升序降序而不返回任何值。

所以问题在于answer = newList.sort()答案是否定的。

相反,您可以这样做return newList.sort()

sort()方法的语法为:

list.sort(key=..., reverse=...)

另外,您也可以出于相同目的使用Python的内置函数sorted()。

sorted(list, key=..., reverse=...)

注意:sort()和sorted()之间最简单的区别是:sort()不返回任何值,而sorted()返回可迭代的列表。

所以就你而言answer = sorted(newList)

To understand why it does not return the list:

sort() doesn’t return any value while the sort() method just sorts the elements of a given list in a specific order – ascending or descending without returning any value.

So problem is with answer = newList.sort() where answer is none.

Instead you can just do return newList.sort().

The syntax of the sort() method is:

list.sort(key=..., reverse=...)

Alternatively, you can also use Python’s in-built function sorted() for the same purpose.

sorted(list, key=..., reverse=...)

Note: The simplest difference between sort() and sorted() is: sort() doesn’t return any value while, sorted() returns an iterable list.

So in your case answer = sorted(newList).


回答 6

如果要返回排序列表,可以使用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)

you can use sorted() method if you want it to return the sorted list. It’s more convenient.

l1 = []
n = int(input())

for i in range(n):
  user = int(input())
  l1.append(user)
sorted(l1,reverse=True)

list.sort() method modifies the list in-place and returns None.

if you still want to use sort you can do this.

l1 = []
n = int(input())

for i in range(n):
  user = int(input())
  l1.append(user)
l1.sort(reverse=True)
print(l1)