Python – 交替後向迭代
簡介
使用 Python 實現交替後向迭代涉及列表資料結構和功能的基本用法,並藉助迴圈結構。此問題應用簡單的數學技能,使我們能夠確定偶數以列印從後側開始的交替數字。Python 語言中提供的資料結構包括列表、元組和字典。它為使用者提供了遍歷不同型別資料結構的功能。最常見的是,for 迴圈用於遍歷列表或元組。
交替後向迭代
在本文中,迭代從給定列表的後部或尾部開始,與從前端開始迭代相比,效率更高。
方法
方法 1 - 使用 for 迴圈
方法 2 - 使用切片方法
方法 3 - 使用 lambda 函式
方法 1:使用 for 迴圈進行 Python 交替後向迭代程式
range() 函式聲明瞭三個引數,它們是給定列表的長度作為 len(list_1)-1,表示列表的最後一個索引,第二個引數是 -1,表示迭代不應超出開頭,最後一個引數是 -1,表示我們必須向後或向尾部移動。
演算法
步驟 1 - 使用整數元素初始化列表。
步驟 2 - 初始化空列表。
步驟 3 - for 迴圈用於從尾部迭代列表的每個元素。
步驟 4 - 使用 len() 函式識別列表的長度,並使用 range() 函式維護元素的範圍。
步驟 5 - 然後,print 語句用於在後向迭代後返回元素列表。
示例
#initializing the list with integer elements
list_1 = [1,2,3,4,5,6,8]
#initializing the empty list
alternate_list = []
#for loop is used to iterate through the loop from the rear using the range() and len() function
for a in range(len(list_1)-1,-1,-2):
alternate_list.append(list_1[a])
#returns the elements of the list iterated from the rear
print("Alternate rear iteration:", alternate_list)
輸出
Alternate rear iteration: [8, 5, 3, 1]
方法 2:使用切片方法進行 Python 交替後向迭代程式
切片方法用於以 -1 的步長遍歷字串。遵循此方法,而不是從左到右迭代。
演算法
步驟 1 - 提示使用者輸入值,並藉助 split() 函式將輸入的整數拆分為單獨的元素。
步驟 2 - 給定的字串只需進行切片方法即可反轉給定的字串。
步驟 3 - 然後,print 語句用於返回字串的反轉字元。
示例
#The user is prompted to enter the integers with proper spaces
#split() function is used to split the given strings into separate ones
list1 = [1, 2, 3, 5, 7, 9, 4]
list1 = [int(a) for a in list1]
#The list of elements given by the user and the string is reversed using the slicing method
alternate_list = list(reversed(list1[::2]))
#printing statement will return the given input in a reversed alternate order
print("Alternate rear iteration:", alternate_list)
輸出
Alternate rear iteration: [4, 7, 3, 1]
方法 3:使用 lambda 函式進行 Python 交替後向迭代程式
在函式的情況下,我們使用 def 函式,但對於匿名函式,我們可以使用 lambda 函式以及 key 引數。lambda 函式通常與 filter() 或 map() 函式一起使用。
演算法
步驟 1 - 提示使用者輸入整數,並在空格之間儲存在名為 list1 的變數中。
步驟 2 - 藉助 split() 函式,將輸入的整數拆分為單獨的元素。
步驟 3 - 使用列表推導式將給定的值字串轉換為整數資料型別。
步驟 4 - 由於 filter 函式總是與 lambda 函式一起使用,因此它從尾部過濾給定的元素列表。
步驟 5 - key 引數“m”用於檢查它是否是偶數。
步驟 6 - 稍後,使用 reversed() 函式反轉轉換後的輸入字串以進行後向迭代過程。
步驟 7 - 然後,print 語句用於在後向迭代後返回元素列表。
示例
#The user is prompted to enter the integers with proper spaces
#split() function is used to split the given strings into separate ones
list1 = [1, 2, 3, 5, 7, 9, 4]
list1 = [int(a) for a in list1]
#lambda function is used to get the alternate rear iteration using filter() and map() function
alternate_list = list(filter(lambda m: list1.index(m) % 2 == 0, reversed(list1)))
#printing statement will return the given input in a reversed alternate order
print("Alternate rear iteration:", alternate_list)
輸出
Alternate rear iteration: [4, 7, 3, 1]
結論
在當今世界,對於資料量龐大的組織來說,處理資料是最具挑戰性的任務,隨著資料科學和機器學習的發展,訪問資料變得更加容易。Python 是一種用途廣泛的高階語言,使用者可以輕鬆理解。
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP