【Python实践-5】使用迭代查找一个list中最小和最大值

时间:2023-03-10 02:41:51
【Python实践-5】使用迭代查找一个list中最小和最大值
 # -*- coding: utf-8 -*-
#使用迭代查找一个list中最小和最大值,并返回一个tuple
#遍历list,找到最小值
def findMinAndMax(L):
if L==[]:
return(None, None)
else:
a=L[0]
b=L[0]
for num in L:
if num<a:
a=num
for num in L:
if num>b:
b=num
return (a,b)
print(findMinAndMax([1,2,3,4,5,6]))
知识点:
迭代: 如果给定一个list或tuple,我们可以通过for循环来遍历这个list或tuple,这种遍历我们称为迭代(Iteration)。 在Python中,迭代是通过for ... in来完成的,而很多语言比如C语言,迭代list是通过下标完成的。 Python的for循环抽象程度要高于C的for循环,因为Python的for循环不仅可以用在list或tuple上,还可以作用在其他可迭代对象上。 只要是可迭代对象,无论有无下标,都可以迭代。