找到你要的答案

Q:whats the deal with x.sort() and x.reverse()? [duplicate]

Q:用X和X sort() reverse()交易是什么?[重复]

This question already has an answer here:

x = [1, 3, 5, 7]
y = [2, 4, 6, 8]
x +=y
x.sort()
print(x.sort())

Every time I try to get an output for this python just returns none. Why is this? I also get the same result when I try to use x.reverse() and the like. Thank you!

这个问题在这里已经有了答案:

x = [1, 3, 5, 7]
y = [2, 4, 6, 8]
x +=y
x.sort()
print(x.sort())

Every time I try to get an output for this python just returns none. Why is this? I also get the same result when I try to use x.reverse() and the like. Thank you!

answer1: 回答1:

x.sort() sorts the list in place, it returns None, it just modifies the order of the list elements. The same goes for x.reverse()

From the docs (https://docs.python.org/2/library/stdtypes.html#typesseq)

  1. The sort() and reverse() methods modify the list in place for economy of space when sorting or reversing a large list. To remind you that they operate by side effect, they don’t return the sorted or reversed list.

These two list's functions should not be confused with more general built-in functions sorted() and reversed(). Which are functions (not method) and can be applied to different objects (not only lists) and return a new object.

Now to answer your question specifically, when you do: `print(x.sort()) you're saying "print the returns value of x.sort()" which is None. You can fix your code by doing:

x.sort()
print x

X sort()排序列表的地方,返回None,它只是修改列表中元素的顺序。同样reverse() X.

从文件(https:/ /文档。Python。org / 2 /图书馆/ stdtypes。HTML # typesseq)

  1. The sort() and reverse() methods modify the list in place for economy of space when sorting or reversing a large list. To remind you that they operate by side effect, they don’t return the sorted or reversed list.

这两个列表的功能不应该用更一般的内置功能sorted()和reversed()困惑。这是函数(不是方法),可以应用到不同的对象(不仅仅是列表)并且返回一个新的对象。

现在专门回答你的问题,当你做`打印(X sort())你说的“打印X sort()”是没有返回值。你可以通过执行来修复代码:

x.sort()
print x
python  list