Python reversed() function returns a reversed iterator from the specified sequence argument.
Python reversed()函数从指定的sequence参数返回反向迭代器。
python reversed() (Python reversed())
Python reversed() function syntax is:
Python reversed()函数语法为:
reversed(seq)
- The input argument must be a sequence, for example tuple, list, string etc. 输入参数必须是一个序列,例如tuple , list , string等。
- The returned object is of type
reversed
and it’s an iterator. 返回的对象是reversed
类型,它是一个迭代器。 - We can supply a custom object as reversed() function argument if it has
__reversed__()
method or supports the sequence protocol. 如果自定义对象具有__reversed__()
方法或支持序列协议,则可以提供它作为reversed()函数参数。 - We need to implement
__len__()
method and the__getitem__()
method with integer arguments starting at 0 to support sequence protocol. 我们需要使用从0开始的整数参数来实现__len__()
方法和__getitem__()
方法,以支持序列协议。
带序列的reversed() (reversed() with sequence)
Let’s look at reversed() function examples with standard sequence objects such as string, bytes, tuple, list etc.
让我们看一下带有标准序列对象(例如字符串, 字节 ,元组,列表等)的reversed()函数示例。
def print_iterator(it):
for x in it:
print(x, end=' ')
print('\n')
# reversed string
r = reversed('abc')
print(type(r))
print(r)
print_iterator(r)
# reversed list
r = reversed([1, 2, 3])
print_iterator(r)
# reversed tuple
r = reversed((1, 2, 3))
print_iterator(r)
# reversed bytes
r = reversed(bytes('abc', 'utf-8'))
print_iterator(r)
# reversed bytearray
r = reversed(bytearray('abc', 'utf-8'))
print_iterator(r)
Output:
输出:
<class 'reversed'>
<reversed object at 0x109d1f208>
c b a
3 2 1
3 2 1
99 98 97
99 98 97
Notice that bytes and bytearray elements are converted to integer while printing on console.
请注意,在控制台上打印时,字节和字节数组元素将转换为整数。
具有具有__reversed__方法的对象的reversed() (reversed() with object having __reversed__ method)
# object with __reversed__ method
class Data:
name = ''
def __init__(self, n):
self.name = n
def __reversed__(self):
return reversed(self.name)
d = Data('ABC')
r = reversed(d)
print_iterator(r)
Output: C B A
输出: CBA
具有对象支持序列协议的reversed() (reversed() with object supporting sequence protocol)
# object supporting sequence protocol i.e.
# implementing __len__() and __getitem__ method
class MyTupleWrapper:
t = ()
def __init__(self, tu):
if not isinstance(tu, tuple):
return ValueError('Only accepts tuple')
self.t = tu
def __len__(self):
return len(self.t)
def __getitem__(self, index):
return self.t[index]
mt = MyTupleWrapper((1, 2, 3, 4))
r = reversed(mt)
print_iterator(r)
Output: 4 3 2 1
输出: 4 3 2 1
Reference: Official Documentation
参考: 官方文档
翻译自: https://www.journaldev.com/23113/python-reversed-function