什么叫做迭代?
我们通过 List 集合的下标来遍历 List 集合中的元素,在 Python 中,给定一个 list 或 tuple,我们可以通过 for 循环来遍历这个 list 或 tuple ,这种遍历就是迭代。
字符串迭代
str = "https://www.baidu.com"
for i in str:
print(i,end=" ")
结果
h t t p s : / / w w w . b a i d u . c o m
列表迭代
lst = [i for i in range(10)]
for i in lst:
print(i, end=" ")
结果:
0 1 2 3 4 5 6 7 8 9
字典迭代
dict = {"name":"wisdom","age":28,"job":"HR","address":{"city":"北京"}}
#取values
for v in dict.values():
print(v,end=" ")
print("\n")
#取key
for k in dict:
print(k,end=" ")
结果:
wisdom 28 HR {'city': '北京'}
name age job address
tuple 元组迭代
tups = (0,1,2,3,4,5)
for i in tups:
print(i,end=" ")
结果:
0 1 2 3 4 5