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中文網其他相關文章!