主要内容 #
1. 遍历的概念 #
遍历就是把可迭代对象(包含字符串、列表、元组、字典等)里的数据成员都逐一访问一遍2. 字符串的遍历 #
通过一层for循环逐一访问字符串里的每一个元素str1 = "dashima" for i in str1: print(i)
3. 列表的遍历(一维列表, 二维列表) #
list1 = [12, 'python', 9, 'C++', '2021', 'dashima', -6] for i in list1: print(i)遍历一维列表,取出最大的数字以及对应的索引:
list1 = [12, 0, 9, 17, 20, 21, 76, 65, 77, 56, 46] maxnum = list1[0] ind = 0 k = 0 for i in list1: if i > maxnum: maxnum = i ind = k k += 1 print("maxnum = ", maxnum) print("index = ", ind)
list2d = [ [1, 3, 5], [2, 4, 6], [5, 2, 0], [7, 9, 8], ] for i in list2d: print(i)通过二层for循环逐一访问二维列表里的每一个元素:
list2d = [ [1, 3, 5], [2, 4, 6], [5, 2, 0], [7, 9, 8], ] for i in list2d: for j in i: print(j)
3. 字典的遍历 #
访问字典的键值:dict1 = {"name": "小明", "birth": "2005/06", "code": 1} for i in dict1: print(i)访问字典的键值对:
dict1 = {"name": "小明", "birth": "2005/06", "code": 1} for i, j in dict1.items(): print("key = ", i, ", value = ", j)
3. 小结 #
OJ训练题 #
1、【入门】与7无关的数 – ★
2、【入门】求数 – ★
3、【入门】求出1~n中满足条件的数的个数和总和? – ★
4、【入门】今天要上课吗 – ★★
5、【例33.2】 两位数 – ★★★