列印Python列表元素的迴圈範圍
列表資料結構包含不同資料型別元素,例如整數、字串或浮點數。一旦在列表資料結構中(方括號內)定義的元素是不可更改的。為了列印列表資料結構中的迴圈範圍,Python語言為使用者提供了一些內建功能。因此,在列表中,我們可以將多個值一起儲存,從而減少複雜的操作。Python基於面向物件程式設計(OOP)概念,由於其簡單的程式碼而受到程式設計師的歡迎。
列印Python列表元素的迴圈範圍
由於列表資料結構由特定範圍內的各種元素組成。如果列表包含10個元素,範圍從0到9,則從某個起點到特定終點列印列表中的元素。使用者還可以提供其必須經歷的功能迭代次數。
方法
方法1 - 使用遞迴函式
方法2 - 使用cycle模組
方法1:使用遞迴函式列印列表元素的迴圈範圍的Python程式
我們定義一個名為circular_range的新函式,它接受三個引數:list1、k和a。“a”引數是可選的,預設為零,此引數用於跟蹤list1中的當前索引位置。
演算法
步驟1 - 函式定義了三個引數:list1、整數first和second。
步驟2 - 建立一個空列表。
步驟3 - 如果當前索引位置“a”等於list1的長度,則退出函式。
步驟4 - 使用巢狀迴圈迭代list1中的下一個k個元素。
步驟5 - 將每個元素追加到ans,注意使用模運算子(%)環繞到列表的開頭。
步驟6 - 列印生成的子列表
步驟7 - 使用更新的a值再次呼叫circular_range函式。
步驟8 - 重複步驟2-7,直到生成長度為k的所有子列表,並且列表定義的值範圍為1到4。
步驟9 - 定義兩個整數並初始化它們的值。
步驟10 - for迴圈將遍歷列表。
步驟11 - 返回一組4個元素,最後,我們列印生成的子列表並再次呼叫circular_range函式,並使用更新的a值。
示例
#defining the function with three parameters
def circular_range(list1, k, a=0):
#To check whether the current index value element is equal to the length of the list
if a == len(list1):
return
#creating an empty list
ans = []
#nested for loop is used to iterate through the list for the next element
for b in range(k):
#Adding the element at the beginning of the list using modulo(%) operator
ans.append(list1[(a+b)%len(list1)])
#prints the answer
print(ans)
#calling the function recursively for all the elements
#The function uses recursion to generate each sublist of length k
circular_range(list1, k, a+1)
#initializing the list with a set of values
list1 = [5, 6, 7, 8]
k = 4
#the function is repeated all the possible elements are printed
circular_range(list1, k)
輸出
[5, 6, 7, 8] [6, 7, 8, 5] [7, 8, 5, 6] [8, 5, 6, 7]
方法2:使用迭代方法列印列表元素的迴圈範圍的Python程式
為了以迴圈方式列印列表中的所有可能範圍的專案,使用了迭代方法。
演算法
步驟1 - 列表是用一系列元素建立的。
步驟2 - 變數設定為4。
步驟3 - for迴圈用於根據範圍迭代列表。
步驟4 - 建立一個新列表以儲存迴圈範圍的列表。
步驟5 - 巢狀for迴圈用於迭代k值的範圍。
步驟6 - 列印所有可能範圍內的迴圈範圍中的最終值列表。
示例
#creating the list with integer elements
list1 = [5, 6, 7, 8]
#declaring the variable k as 4
k = 4
#iteration through the list using the len function
for a in range(len(list1)):
#initializing the empty list
ans = []
#nested for loop to iterate using the “k”
for b in range(k):
ans.append(list1[(a+b)%len(list1)])
#final list with a circular range is printed
print(ans)
輸出
[5, 6, 7, 8] [6, 7, 8, 5] [7, 8, 5, 6] [8, 5, 6, 7]
結論
Python廣泛應用於機器學習和人工智慧等多種技術中。這些方法幫助程式設計師列印列表中迴圈範圍內的所有元素。資料處理是當前技術中最突出的一個方面,在迴圈範圍內列印元素是基本函式之一。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP