Why does “return list.sort()” return None, not the list?
我已经能够验证
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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 |
1 2 | newList.sort() return newList |
问题出在这里:
1 | answer = newList.sort() |
采用:
1 | answer = sorted(newList) |
以下是来自Guido van Rossum的电子邮件,在python的开发列表中解释为什么他选择不返回
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:
1 x.compress().chop(y).sort(z)which would be the same as
1
2
3 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:
1
2 y = x.rstrip("
").split(":").lower()
Python有两种排序:排序方法(或"成员函数")和排序函数。 sort方法对名为的对象的内容进行操作 - 将其视为对象重新排序的动作。 sort函数是对对象表示的数据的操作,并按排序顺序返回具有相同内容的新对象。
给定一个名为
1 2 3 4 | >>> l = [1, 5, 2341, 467, 213, 123] >>> l.sort() >>> l [1, 5, 123, 213, 467, 2341] |
此方法没有返回值。但是,如果我们尝试分配
1 2 3 4 | >>> l = [1, 5, 2341, 467, 213, 123] >>> r = l.sort() >>> print(r) None |
另一方面,函数
1 2 3 4 5 6 | >>> l = [1, 5, 2341, 467, 213, 123] >>> r = sorted(l) >>> l [1, 5, 2341, 467, 213, 123] >>> r [1, 5, 123, 213, 467, 2341] |
请注意,返回的值不是深层副本,因此请像往常一样对列表中包含的元素进行副作用操作时要小心:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | >>> 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习惯性地从改变数据的函数和方法返回
如果要获取可迭代并返回其项的新排序列表,请使用
要理解为什么它不返回列表:
sort()不会返回任何值。
sort()方法只按特定顺序对给定列表的元素进行排序 - 升序或降序而不返回任何值。
问题是
相反,你可以做
sort()方法的语法是:
1 | list.sort(key=..., reverse=...) |
或者,您也可以使用Python的内置函数sorted()来实现相同的目的。
1 | sorted(list, key=..., reverse=...) |
注意:sort()和sorted()之间最简单的区别是:sort()不返回任何值,而sorted()返回可迭代列表。
所以在你的情况下