为什么 Python 有内置函数 reversed

为什么不直接使用 x[::-1] 而不是 reversed(x)

编辑 :@TanveerAlam pointed out reversed 实际上不是一个函数,而是一个类,尽管被列在 Built-in Functions 页面上。

最佳答案

reversed 返回一个反向迭代器。
[::-1] 向对象请求切片

Python 对象尝试返回您可能期望的内容

>>> [1, 2, 3][::-1]
[3, 2, 1]
>>> "123"[::-1]
'321'

这很方便 - 特别是对于字符串和元组。

但请记住,大多数代码不需要反转字符串。
reversed() 最重要的作用是 使代码更易于阅读和理解

它返回一个迭代器而不创建新序列的事实是次要的

From the docs


>>>
>>> for i in reversed(xrange(1,4)):
...    print i
...
3
2
1


>>>
>>> input = open('/etc/passwd', 'r')
>>> for line in reversed(list(input)):
...   print line
...

关于python - 为什么 Python 有 `reversed` ?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26985749/

10-11 04:16