遍历
通过for ... in ...:或者while的语法结构,将字符串、列表、元组、字典等数据结构中的元素循环输出,这种方式就是遍历。
注意python语法的缩进
1.1 字符串遍历
示例1:
a_str = "hello"
for char in a_str:
print(char)
结果:
h
e
l
l
o
示例2:
a_str = "hello"
length = len(a_str )
i = 0
while i<length:
print(a_str [i])
i+=1
结果:
xiaoWang
xiaoZhang
xiaoHua
1.2 列表遍历
示例1:
namesList = ['xiaoWang','xiaoZhang','xiaoHua']
for name in namesList:
print(name)
结果:
xiaoWang
xiaoZhang
xiaoHua
示例2:
namesList = ['xiaoWang','xiaoZhang','xiaoHua']
length = len(namesList)
i = 0
while i<length:
print(namesList[i])
i+=1
结果:
xiaoWang
xiaoZhang
xiaoHua
1.3 元组遍历
示例1:
a_turple = ['xiaoWang','xiaoZhang','xiaoHua']
for name in a_turple :
print(name)
结果:
xiaoWang
xiaoZhang
xiaoHua
示例2:
a_turple = ['xiaoWang','xiaoZhang','xiaoHua']
length = len(a_turple )
i = 0
while i<length:
print(a_turple[i])
i+=1
结果:
h
e
l
l
o
1.4 字典遍历
<1> 遍历字典的key(键)
dict = {'name':'wang','sex':'m','age':20}
for key in dict.keys():
print(key)
结果:
age
name
sex
<2> 遍历字典的value(值)
dict = {'name':'wang','sex':'m','age':20}
for value in dict.values():
print(value)
结果:
20
wang
m
<3> 遍历字典的项(元素)
dict = {'name':'wang','sex':'m','age':20}
for item in dict.items():
print(item)
结果:
('age', 20)
('name', 'wang')
('sex', 'm')
<4> 遍历字典的key-value(键值对)
dict = {'name':'wang','sex':'m','age':20}
for key, value in dict.items():
print(key,value)
结果:
sex m
name wang
age 20
1.5 集合遍历
示例1:
set= set(['a', 'b', 'c', 'd'])
for s in set:
print (s)
结果:
c
d
a
b
示例2:
a_set = (['a', 'b', 'c', 'd'])
length = len(a_set)
i = 0
while i<length:
print(a_set[i])
i+=1
结果:
a
b
c
d