可迭代类型:
list、tuple
d = list(range(101))
for i in d:
print(i)
d = tuple(range(101))
for i in d:
print(i)
dict
对key 进行迭代:
d = {'a': 1 ,'b': 2, 'c':3}
for key in d:
print(key)
对value进行迭代:
d = {'a': 1 ,'b': 2, 'c':3}
for value in d.values():
print(value)
str
s = 'ABC'
for i in s:
print(i)
对于对象是否可迭代的检查方法:
from collections import Iterable
isinstance('abc',Iterable)
isinstance('[1,2,3]',Iterable)
isinstance(123,Iterable)
isinstance('123',Iterable)
下标循环方法enumerate,赋予list中的元素以对应的索引值,形成索引:元素值对
for i , value in enumerate(['A', 'B', 'C']):
print(i, value)
输出结果为
0 A
1 B
2 C
带多元素的循环
for x, y in ([(1,2),(2,3),(3,4)]):
print(x, y)
for x, y, z in ([(1,2,3),(2,3,4),(3,4,5)]):
print(x, y,z)
++练习题:
def findMinAndMax(L):
if L != []:
max = L[0]
min = L[0]
for l in L:
if max < l:
max = l
if min > l:
min = l
return (min, max)
else:
return (None, None)
# 测试
if findMinAndMax([]) != (None, None):
print('测试失败!++++1')
elif findMinAndMax([7]) != (7, 7):
print('测试失败!++++2', findMinAndMax([7]))
elif findMinAndMax([7, 1]) != (1, 7):
print('测试失败!++++3', findMinAndMax([7, 1]))
elif findMinAndMax([7, 1, 3, 9, 5]) != (1, 9):
print('测试失败!++++4', findMinAndMax([7, 1, 3, 9, 5]))
else:
print('测试成功!')