Python 列表(list)遍历 | 您所在的位置:网站首页 › 如何循环遍历list › Python 列表(list)遍历 |
Python列表(list)遍历教程
Python 的 列表 的遍历有四种方法:使用 for循环 遍历、使用 range 遍历、使用 enumerate 遍历以及使用 iter 遍历。 Python for循环遍历列表详解 语法 for item in list: pass 参数 参数 描述 item 遍历得到的每一个元素。 list 需要遍历的列表。 说明使用 for 循环遍历列表,列表的每一个元素是 item。 Python range遍历列表详解 语法 for index in range(len(list)): pass 参数 参数 描述 index 遍历到的列表的索引。 list 需要被遍历的列表。 说明使用 range 遍历列表,index 是列表的每一个元素的索引。 Python enumerate遍历列表详解 语法 for index,value in enumerate(list): pass 参数 参数 描述 index 遍历列表得到的索引。 value 遍历列表得到的每一个列表的元素。 list 需要被遍历的列表。 说明使用 enumerate 遍历列表,index 是列表的索引,value 是列表的索引对应的值。 Python iter遍历列表详解 语法 for item in iter(list): pass 参数 参数 描述 item 遍历得到的每一个元素。 list 需要遍历的列表。 说明使用 iter 遍历列表,列表的每一个元素是 item。 案例 Python for循环遍历列表使用 Python for循环遍历列表 print("嗨客网(www.haicoder.net)") # 使用 Python for循环遍历列表 lis = ["Hello", "HaiCoder", 1024] for item in lis: print("Item =", item)程序运行后,控制台输出如下: 我们使用 [] 创建了一个列表 lis,列表的第一个和第二个元素都是 string 类型,第三个元素是 int 类型的。接着,我们使用 for 循环的形式遍历元祖的每一个元素,并使用 Print 打印每一个元素。 Python range遍历列表使用 Python range 遍历列表 print("嗨客网(www.haicoder.net)") # 使用 Python range遍历列表 lis = ["Hello", "HaiCoder", 1024] for index in range(len(lis)): print("index =", index, "value =", lis[index])程序运行后,控制台输出如下: 我们使用 [] 创建了一个列表 lis,列表的第一个和第二个元素都是 string 类型,第三个元素是 int 类型的。接着,我们使用 range 生成列表的索引的数列,最后,使用列表的索引的形式获取列表的每一个元素。 Python enumerate遍历列表使用 Python enumerate 遍历列表 print("嗨客网(www.haicoder.net)") # 使用 Python enumerate遍历列表 lis = ["Hello", "HaiCoder", 1024] for index, value in enumerate(lis): print("index =", index, "value =", value)程序运行后,控制台输出如下: 我们使用 [] 创建了一个列表 lis,列表的第一个和第二个元素都是 string 类型,第三个元素是 int 类型的。接着,我们使用 enumerate 遍历列表,获取列表的每一项的索引以及索引对应的值。 Python iter遍历列表使用 Python iter 遍历列表 print("嗨客网(www.haicoder.net)") # 使用 Python iter遍历列表 lis = ["Hello", "HaiCoder", 1024] for value in iter(lis): print("value =", value)程序运行后,控制台输出如下: 我们使用 [] 创建了一个列表 lis,列表的第一个和第二个元素都是 string 类型,第三个元素是 int 类型的。接着,我们使用 iter 遍历列表,获取列表的每一项的值。 Python列表(list)遍历总结Python 的列表的遍历有四种方法:使用 for 循环遍历、使用 range 遍历、使用 enumerate 遍历以及使用 iter 遍历。Python for 循环遍历列表语法: for item in list: passPython range 遍历列表语法: for index in range(len(list)): passPython enumerate 遍历列表语法: for index,value in enumerate(list): passPython iter 遍历列表语法: for item in iter(list): pass |
CopyRight 2018-2019 实验室设备网 版权所有 |