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中以相反的顺序迭代一个序列?的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!