Python——用for_while遍历列表

遍历列表可以逐个处理列表元素,通常使用 for 循环和 while 循环来实现。

用 for 循环遍历列表:

#ex0503.py
lst = ['primary school','secondary school','high school','collage']
for item in lst:
    print(item,end = ',')

使用 while 循环遍历列表,需要先获取列表长度,将获得的长度作为循环的条件。

用 while 循环遍历列表:

#ex0504.py
lst = list(range(2,21,3))
i = 0
result = []
while i < len(lst):
    result.append(lst[i]*lst[i])
    i += 1
print(result)

你可能感兴趣的:(Python知识体系,python,开发语言)