打印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