reversed()
函数返回一个迭代器对象,该对象以相反的顺序访问可迭代对象(列表、元组、字符串等)的元素。
示例
string = 'Python'
result = reversed(string)
# convert the iterator to list and print it
print(list(result))
# Output: ['n', 'o', 'h', 't', 'y', 'P']
reversed() 语法
reversed()
的语法是
reversed(iterable)
reversed()
函数接受一个参数。
- iterable - 可迭代对象,例如列表、元组、字符串、字典等。
reversed() 返回值
reversed()
方法返回一个迭代器对象。
注意:迭代器对象可以轻松转换为序列,例如列表和元组。它们也可以直接使用循环进行迭代。
示例 1:以相反顺序访问项目
text = 'cad'
# access items of the string in reversed order
for char in reversed(text):
print(char)
输出
d a c
示例 2:反转字典键
country_capitals = {
'England': 'London',
'Canada': 'Ottawa',
'Germany': 'Berlin'
}
# access keys in reversed order
# and convert it to a tuple
country = tuple(reversed(country_capitals))
print(country)
输出
('Germany', 'Canada', 'England')
另请阅读