Python reversed()

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')

另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战