本文共 2498 字,大约阅读时间需要 8 分钟。
Python reversed() function returns a reversed iterator from the specified sequence argument.
Python reversed()函数从指定的sequence参数返回反向迭代器。
Python reversed() function syntax is:
Python reversed()函数语法为:
reversed(seq)
reversed
and it’s an iterator. 返回的对象是reversed
类型,它是一个迭代器。 __reversed__()
method or supports the sequence protocol. 如果自定义对象具有__reversed__()
方法或支持序列协议,则可以提供它作为reversed()函数参数。 __len__()
method and the __getitem__()
method with integer arguments starting at 0 to support sequence protocol. 我们需要使用从0开始的整数参数来实现__len__()
方法和__getitem__()
方法,以支持序列协议。 Let’s look at reversed() function examples with standard sequence objects such as string, , tuple, list etc.
让我们看一下带有标准序列对象(例如字符串, ,元组,列表等)的reversed()函数示例。
def print_iterator(it): for x in it: print(x, end=' ') print('\n')# reversed stringr = reversed('abc')print(type(r))print(r)print_iterator(r)# reversed listr = reversed([1, 2, 3])print_iterator(r)# reversed tupler = reversed((1, 2, 3))print_iterator(r)# reversed bytesr = reversed(bytes('abc', 'utf-8'))print_iterator(r)# reversed bytearrayr = reversed(bytearray('abc', 'utf-8'))print_iterator(r)
Output:
输出:
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.
请注意,在控制台上打印时,字节和字节数组元素将转换为整数。
# object with __reversed__ methodclass 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
# object supporting sequence protocol i.e.# implementing __len__() and __getitem__ methodclass 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:
参考:
翻译自:
转载地址:http://oqmzd.baihongyu.com/