Python为什么有“reversed”?

2024-09-29 19:30:01 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么Python有内置函数^{}?在

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


编辑@TanveerAlampointed outreversed实际上不是一个函数,而是一个类,尽管它被列在Built-in Functions页面上。在


Tags: 函数in编辑页面functions内置builtreversed
3条回答

反向返回反向迭代器。

x[::-1]返回列表。

In [1]: aaa = [1,2,3,4,5]

In [4]: aaa[::-1]
Out[4]: [5, 4, 3, 2, 1]

In [5]: timeit(aaa[::-1])
1000000 loops, best of 3: 206 ns per loop

In [6]: reversed(aaa)
Out[6]: <listreverseiterator at 0x104310d50>

In [7]: timeit(reversed(aaa))
10000000 loops, best of 3: 182 ns per loop

reversed返回反向迭代器。在

[::-1]向对象请求切片

Python对象尝试返回您可能期望的结果

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

这很方便,尤其是对于字符串和元组。在

但请记住,大多数代码不需要反转字符串。在

reversed()最重要的作用是使代码更易于阅读和理解。在

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

From the docs

PEP 322: Reverse Iteration A new built-in function, reversed(seq)(), takes a sequence and returns an iterator that loops over the elements of the sequence in reverse order.

^{pr2}$

Compared to extended slicing, such as range(1,4)[::-1], reversed() is easier to read, runs faster, and uses substantially less memory.

Note that reversed() only accepts sequences, not arbitrary iterators. If you want to reverse an iterator, first convert it to a list with list().

>>>
>>> input = open('/etc/passwd', 'r')
>>> for line in reversed(list(input)):
...   print line
...
>>> a= [1,2,3,4,5,6,7,8,9,10]
>>> a[::-1]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> reversed(a)
<listreverseiterator object at 0x10dbf5390>

第一种表示法是急切地生成反向;第二种表示法是给您一个反向迭代器,这可能更便宜,因为它有可能只在需要时生成元素

相关问题 更多 >

    热门问题