在python中,迭代通过 for...in完成,如:
>>>for ch in 'ABC':
print(ch)
A
B
C
判断一个对象是否是可迭代对象: collections模块的Iterable类型
>>>from collections import Iterable
>>>isinstance('abc',Iterable)
True
>>>isinstace(123,Iterable)
False
实现两个变量的迭代:
>>>for i,value in enumerate(['A','B','C']):
print(i,value)
0 A
1 B
2 C
使用迭代查找一个list中最小值和最大值,并返回一个tuple:
def findMinAndMax(L):
if L==[]:
return (None,None)
else:
Min=L[0]
Max=L[0]
for value in L:
if value<Min:
Min=value
if value>Max:
Max=value
return (Min,Max)
#测试
if findMinAndMax([]) != (None, None):
print('测试失败!')
elif findMinAndMax([7]) != (7, 7):
print('测试失败!')
elif findMinAndMax([7, 1]) != (1, 7):
print('测试失败!')
elif findMinAndMax([7, 1, 3, 9, 5]) != (1, 9):
print('测试失败!')
else:
print('测试成功!')