首页 >后端开发 >Python教程 >如何在Python中以相反的顺序迭代一个序列?

如何在Python中以相反的顺序迭代一个序列?

WBOY
WBOY转载
2023-08-25 20:57:10766浏览

如何在Python中以相反的顺序迭代一个序列?

Python 序列包括字符串、列表、元组等。我们可以使用不同的方式合并 Python 序列的元素。让我们看一些以相反顺序迭代列表的示例。

使用while循环以逆序迭代

示例

在这个例子中,我们有一个作为序列的列表,并使用while循环以相反的顺序进行迭代 -

# Creating a List
mylist = ["Jacob", "Harry", "Mark", "Anthony"]

# Displaying the List
print("List = ",mylist)

# Length - 1
i = len(mylist) - 1

# Iterate in reverse order
print("Display the List in Reverse order = ")
while i >= 0 :
   print(mylist[i])
   i -= 1

输出

List =  ['Jacob', 'Harry', 'Mark', 'Anthony']
Display the List in Reverse order = 
Anthony
Mark
Harry
Jacob

使用for循环以逆序迭代

示例

在这个例子中,我们有一个作为序列的列表,并使用for循环以相反的顺序进行迭代-

# Creating a List
mylist = ["Jacob", "Harry", "Mark", "Anthony"]

# Displaying the List
print("List = ",mylist)

# Iterate in reverse order
print("Display the List in Reverse order = ")
for i in range(len(mylist) - 1, -1, -1):
   print(mylist[i])

输出

List =  ['Jacob', 'Harry', 'Mark', 'Anthony']
Display the List in Reverse order = 
Anthony
Mark
Harry
Jacob

使用reverse()逆序迭代

示例

在这个例子中,我们有一个List作为一个序列,并使用reversed()方法以相反的顺序进行迭代 -

# Creating a List
mylist = ["Jacob", "Harry", "Mark", "Anthony"]

# Displaying the List
print("List = ",mylist)

# Iterate in reverse order using reversed()
print("Display the List in Reverse order = ")
[print (i) for i in reversed(mylist)]

输出

List =  ['Jacob', 'Harry', 'Mark', 'Anthony']
Display the List in Reverse order = 
Anthony
Mark
Harry
Jacob

使用负索引进行反向迭代

示例

在此示例中,我们将 List 作为序列,并使用负索引以相反顺序迭代它 

# Creating a List
mylist = ["Jacob", "Harry", "Mark", "Anthony"]

# Displaying the List
print("List = ",mylist)

# Iterate in reverse order using negative indexing
print("Display the List in Reverse order = ")
[print (i) for i in mylist[::-1]]

输出

List =  ['Jacob', 'Harry', 'Mark', 'Anthony']
Display the List in Reverse order = 
Anthony
Mark
Harry
Jacob

以上是如何在Python中以相反的顺序迭代一个序列?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除