Python for循环通过序列索引迭代过程解析

Laura ·
更新时间:2024-09-21
· 796 次阅读

这篇文章主要介绍了Python for循环通过序列索引迭代过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

Python for 循环通过序列索引迭代:

注:集合 和 字典 不可以通过索引进行获取元素,因为集合和字典都是无序的。

使用 len (参数) 方法可以获取到遍历对象的长度。

程序:

strs = "Hello World." # 使用 len 方法可以获取到遍历对象的长度。 print(len(strs)) # 12 lst = [7,8,9,4,5,6] print(len(lst)) # 6 tup = (1,2,3,7,8,9) print(len(tup)) # 6

使用 range 方法(左闭右开):

range 函数参数如下,起始位置、终止位置(不包含)、步长。

  注:起始位置默认为 0 。

    步长可以为负,默认为 1。

程序:

# range 函数 (起始位置,终止位置,步长) #   注:起始位置默认为 0 。 #     步长可以为负,默认为 1。 lst = [i for i in range(5)] print(lst) # 起始位置默认为 0 # [0, 1, 2, 3, 4] lst = [i for i in range(1,5)] print(lst) # 不包含终止位置 # [1, 2, 3, 4] lst = [i for i in range(1,5,2)] print(lst) #步长可以根据自己需要进行更改 # [1, 3] lst = [i for i in range(-5,-1,1)] print(lst) # 起始位置和终止位置可以为负 # [-5, -4, -3, -2] lst = [i for i in range(8,5,-1)] print(lst) # 步长可以为负 # [8, 7, 6]

通过序列索引进行迭代操作程序:

字符串:

strs = "Hello World." for i in range(len(strs)): print(strs[i],end = " ") # H e l l o W o r l d .

列表:

lst = [7,8,9,4,5,6] for i in range(len(lst)): print(lst[i],end = " ")

元组:

tup = (1,2,3,7,8,9) for i in range(len(lst)): print(lst[i],end = " ") 您可能感兴趣的文章:python中从for循环延申到推导式的具体使用如何获取Python简单for循环索引浅析python中while循环和for循环Python for循环及基础用法详解python for循环remove同一个list过程解析python中for循环把字符串或者字典添加到列表的方法Python中一个for循环循环多个变量的示例python用for循环求和的方法总结



迭代 python for循环 for 索引 for循环 Python

需要 登录 后方可回复, 如果你还没有账号请 注册新账号