1.遍历列表中的元素:用for(操作元素)和while(操作索引)实现
#将列表中的所有元素打印出来 #for循环主要结合成员运算符使用,此时只能操作元素 list1= ["and",567,"abc"] for element in list1: print(element) else: print("over") #用while实现,操作的是列表索引 num = 0 while num < len(list1): print(list1[num]) num += 1
2.列表生成器的使用
#列表生成器:生成具有一定规律的列表,此时可操作列表索引 indexList = range(0,len(list1)) #range([start,]end[,step]),其中start和step可不写,默认为0和1 for i in indexList: print(i) print(list1[i])
3.练习for循环和列表生成器的结合使用 ,枚举的使用
#练习: #1.计算1~100之间所有整数的和 sum = 0 indexList1 = range(1,101) for i in indexList1: sum += i print(sum) #2.计算1~100之间所有偶数的和 sum = 0 indexList2 = range(0,101,2) for i in indexList2: sum += i print(sum) #枚举:同时遍历索引和元素 for i,element in enumerate(list1): print(i,element)
4.二维列表的遍历:用for循环的方法
#二维列表的遍历 list2 = [[23,54,64,6],[54,4,65],[54,65,657]] subList = list2[1] print(subList[1]) print(list2[1][1]) #嵌套for循环 for subelement in list2: for element in subelement: print(element)
5.练习:乘法表、特定整数之和、列表元素的遍历和删除
#练习: #1.写乘法表 for x in range(1,10): for y in range(1,x + 1): print("%d*%d=%d"%(y,x,x*y),end=" ") print("") #2.计算从1到100以内所有能被3或者17整除的和并输出% sum = 0 for i in range(1,101,1): if i % 3 == 0 or i % 17 == 0: sum += i print(sum) #3.计算从1到100以内能被7或者3整除但不能同时被这两者整除的数的个数 sum = 0 for i in range(1,101,1): if (i % 3 == 0 or i % 7 == 0) and i % 21 != 0 : sum += i print(sum) #需求一:逐一显示列表中索引为奇数的元素;需求二:将属于一个列表且不属于另外一个列表的元素,重新定义一个新的列表 #需求三:已知列表namelist=['stu1','stu2','stu3','stu4','stu5','stu6','stu7'],删除列表 #removelist=['stu3','stu7','stu9'];将属于removelist列表中的每个元素从namelist中移除 List1 = ["sun","mon","tue","wed","thu","fri","sat"] for i in range(len(List1)): if i % 2 != 0: print(List1[i]) List2 = ["sun","mon","tue","fri","sat"] List3 = [] for i in List1: if i not in List2: List3.append(i) print(List3) namelist = ['stu1','stu2','stu3','stu4','stu5','stu6','stu7'] removelist = ['stu3','stu7'] for i in range(len(removelist)): namelist.remove(removelist[i]) print(namelist)