自学Python-for循环

2024-10-14 16:04:58

1、按成员循环。for,和一个成员运算符in的表达式组成的;------------------------------------------------list_A=[1,2,3,34,67,44]for a in list_A: print(a,end=",")输出:1,2,3,34,67,44,------------------------------------------------例子中 a作为成员变量,每次循环按次序拿出列表中的一个元素赋值给变量a,作为函数print的参数。

自学Python-for循环

3、enumerate(序列对象,开始索引):功能是列举出序列中元素的索引,和对应的元素;看个例子:要求胃申赜驵取出序列的索引和对应的值,重新生成一个列表;1)可以按上例2索引循环来完成这个操作:----------------------------------------------------------item_list=['百度百科',"百度经验","百度知道","百度脑图"]newList1=[]for i in range(0,len(item_list)): newItem=(i,item_list[i]) newList1.append(newItem)print('newList1:',newList1)输出:newList1: [(0, '百度百科'), (1, '百度经验'), (2, '百度知道'), (3, '百度脑图')]---------------------------------------------------------2)也可用enumerate函数,看起来会更直观:---------------------------------------------------------item_list=['百度百科',"百度经验","百度知道","百度脑图"]newList2=[]for index, item in enumerate(item_list,0): newList2.append((index,item))print('newList2:',newList2)输出:newList2: [(0, '百度百科'), (1, '百度经验'), (2, '百度知道'), (3, '百度脑图')]---------------------------------------------------------这里用了两个变量index和item,在每次循环,分别接收成员的索引,和成员;

自学Python-for循环
猜你喜欢