【Python实践-5】使用迭代查找一个

发布时间:2019-05-30 21:09:49编辑:auto阅读(2143)

     1 # -*- coding: utf-8 -*-
     2 #使用迭代查找一个list中最小和最大值,并返回一个tuple
     3 #遍历list,找到最小值
     4 def findMinAndMax(L):
     5     if L==[]:
     6         return(None, None)
     7     else:
     8         a=L[0]
     9         b=L[0]
    10         for num in L:
    11            if num<a:
    12                a=num
    13         for num in L:
    14             if num>b:
    15                 b=num
    16         return (a,b)
    17 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上,还可以作用在其他可迭代对象上。 只要是可迭代对象,无论有无下标,都可以迭代。

关键字

上一篇: Python库的安装

下一篇: Flask中的CBV