Python 序列包括字符串、列表、元组等。我们可以使用不同的方式合并 Python 序列的元素。让我们看一些以相反顺序迭代列表的示例。
在这个例子中,我们有一个作为序列的列表,并使用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循环以相反的顺序进行迭代-
# 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
在这个例子中,我们有一个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中文网其他相关文章!