python3(4)

您所在的位置:网站首页 for循环遍历列表python python3(4)

python3(4)

2023-09-05 20:08| 来源: 网络整理| 查看: 265

 

python遍历数组的两种方法 第一种,最常用的,通过for in遍历数组。其实本质就是取出来的是这个数组或者列表中的元素,和角标无关。

colours = ["red","green","blue"]   for colour in colours:       print colour      # red   # green   # blue  

下面的方法可以先获得数组的长度,然后根据索引号遍历数组,同时输出索引号。

其实这种和java的数组遍历很像,用角标取出每个元素来使用。

colours = ["red","green","blue"]   for i in range(0, len(colours)):       print i, colour[i]      # 0 red   # 1 green   # 2 blue  

for i in range(0, len(colours)): 就代表从0开始,如果想从1开始就,就改成for i in range(1, len(colours)):

转载:https://blog.csdn.net/ime2224/article/details/79044607

 

以下是如何用python倒叙遍历一个list

C语言中从后往前遍历数组是很方便的,如:

for(int i = 5; i >= 0; i--){     printf("%d\n", i); } 但是在python中默认是从前往后遍历列表的,有时候需要从后往前遍历。根据 range 函数的用法:

range(start, end[, step])

python中从后往前遍历列表的方法为:

lists = [0, 1, 2, 3, 4, 5] # 输出 5, 4, 3, 2, 1, 0 for i in range(5, -1, -1):     print(lists[i])   # 输出5, 4, 3 for i in range(5, 2, -1):     print(lists[i])

从最后遍历到最前面,就是

for i in range(len(lists)-1, -1, -1):

转载:https://blog.csdn.net/xia_ri_xing/article/details/83822679



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3