Why list reverse returns Null?
本问题已经有最佳答案,请猛点这里访问。
我有这样的示例列表:
1 2 3 4 | l = [1,2,3] print(l.reverse()) #give None instead [3, 2, 1] |
这是怎么回事?我怎样才能反转列表?
How can I reverse list?
名单正被颠倒。但是,
1 2 3 4 | >>> l = [1,2,3] >>> l.reverse() >>> print(l) >>> [3, 2, 1] |
如果有疑问,请使用帮助:
1 2 3 4 5 | >>> help(list.reverse) Help on method_descriptor: reverse(...) L.reverse() -- reverse *IN PLACE* |
(python 2.7文档)
从文档:
list. reverse ()Reverse the elements of the list, in place.
You might have noticed that methods like
insert ,remove orsort that only modify the list have no return value printed – they return the defaultNone . This is a design principle for all mutable data structures in Python.
python不是函数式编程语言,它是必要的。当您调用
1 2 3 4 | l = [1,2,3] l.reverse() print l # prints [3, 2, 1] |
一种返回EDCOX1(3)的方法类似于C/C++ +/Java世界中的EDCOX1·4函数/方法。由于
正如@ys-l在他的评论中指出的,您可以使用python的列表切片表示法来创建列表的反向副本:
1 2 3 | l = [1,2,3] print l[::-1] # prints [3, 2, 1] |