Python程式:從列表中移除並列印每第三個元素,直到列表為空?
在這篇文章中,我們將學習如何使用 Python 程式從列表中移除並列印每第三個元素或專案,直到列表為空。
首先,我們建立一個列表,起始地址的索引為 0,第一個第三個元素的位置為 2,需要遍歷直到列表為空,另一個重要的工作是在每次找到下一個第三個元素的索引並列印其值後,縮短列表的長度。
輸入-輸出場景
以下是從列表中移除並列印每第三個元素直到列表為空的輸入和輸出場景 -
Input: [15,25,35,45,55,65,75,85,95] Output : 35,65,95,45,85,55,25,75,15
這裡,第一個第三個元素是 35,接下來我們從 44 開始計算第二個第三個元素,它是 65,依此類推,直到到達 95。計數再次從 15 開始,用於下一個第三個元素,它是 45。透過以與之前相同的方式繼續,我們到達了 45 之後的第三個元素,它是 85。重複此過程,直到列表完全為空。
演算法
以下是關於如何從列表中移除並列印每第三個元素或專案直到列表為空的演算法或方法 -
列表的索引從 0 開始,第一個第三個元素將位於位置 2。
查詢列表的長度。
遍歷直到列表為空,並且每次查詢下一個第三個元素的索引。
程式結束。
示例
使用者輸入
以下是上述步驟的說明 -
# To remove to every third element until list becomes empty def removenumber(no): # list starts with # 0 index p = 3 - 1 id = 0 lenoflist = (len(no)) # breaks out once the # list becomes empty while lenoflist > 0: id = (p + id) % lenoflist # removes and prints the required # element print(no.pop(id)) lenoflist -= 1 # Driver code A=list() n=int(input("Enter the size of the array ::")) print("Enter the INTEGER number") for i in range(int(n)): p=int(input("n=")) A.append(int(p)) print("After remove third element, The List is") # call function removenumber(A)
輸出
以下是上述程式碼的輸出 -
Enter the size of the array ::9 Enter the number n=10 n=20 n=30 n=40 n=50 n=60 n=70 n=80 n=90 After remove third element, The List is 30 60 90 40 80 50 20 70 10
示例
靜態輸入
以下是一個透過提供靜態輸入從列表中移除並列印每第三個元素直到列表為空的示例 -
# To remove to every third element until list becomes empty def removenumber(no): # list starts with # 0 index p = 3 - 1 id = 0 lenoflist = (len(no)) # breaks out once the # list becomes empty while lenoflist > 0: id = (p + id) % lenoflist # removes and prints the required # element print(no.pop(id)) lenoflist -= 1 # Driver code elements = [15,25,35,45,55,65,75,85,95] # call function removenumber(elements)
輸出
以下是上述程式碼的輸出 -
35 65 95 45 85 55 25 75 15
廣告