reversed()方法返回一個迭代器,該迭代器以相反的順序訪問給定的序列。
用法:
reversed(sequ)
參數:
- sequ:順序要顛倒。
返回值:
returns an iterator that accesses the given sequence in the reverse order.
代碼1
# Python code to demonstrate working of
# reversed()
# For string
seqString = 'geeks'
print(list(reversed(seqString)))
# For tuple
seqTuple = ('g', 'e', 'e', 'k', 's')
print(list(reversed(seqTuple)))
# For range
seqRange = range(1, 5)
print(list(reversed(seqRange)))
# For list
seqList = [1, 2, 4, 3, 5]
print(list(reversed(seqList)))
輸出:
['s', 'k', 'e', 'e', 'g'] ['s', 'k', 'e', 'e', 'g'] [4, 3, 2, 1] [5, 3, 4, 2, 1]
代碼2
vowels = ['a', 'e', 'i', 'o', 'u']
# Function to reverse the list
def __reversed__(self):
return reversed(self.vowels)
# Main Function
if __name__ == '__main__':
print(list(reversed(vowels)))
輸出:
['u', 'o', 'i', 'e', 'a']
相關用法
- Python tell()用法及代碼示例
- Python ord()用法及代碼示例
- Python sum()用法及代碼示例
- Python id()用法及代碼示例
- Python int()用法及代碼示例
- Python map()用法及代碼示例
- Python dir()用法及代碼示例
- Python cmp()用法及代碼示例
- Python oct()用法及代碼示例
- Python hex()用法及代碼示例
注:本文由純淨天空篩選整理自pawan_asipu大神的英文原創作品 Python reversed() function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。