美文网首页python3
python中for循环和len函数的使用

python中for循环和len函数的使用

作者: icessun | 来源:发表于2018-07-13 15:56 被阅读0次
    dinnersPerson = ['icessun', 'Bob', 'Ben', 'alex','rose','jack','flank']
    def sorryName():
        for item in dinnersPerson:
            if(len(dinnersPerson) > 2):
                print('Sorry!!!'+dinnersPerson.pop()+',由于台风的原因,不能邀请你')
    sorryName()
    print(len(dinnersPerson))  #  3
    print(dinnersPerson) #  ['icessun', 'Bob', 'Ben']
    

    当看到这段代码的时候,你是不是觉得应该最后执行的结果列表的长度是2,列表最后只剩下['icessun', 'Bob']

    其实一开始我也是这么想的,后来调试了一下,发现想当然的一些认为是错误的:每次pop之后,for循环又从头开始执行了。这个想法是错误的。

    启动了for循环,那么就会按照列表的顺序依次往下执行,for从列表的前面走,pop从列表的后面走,列表的长度是固定的。循环完毕,尽管条件语句还成立,但是也执行完毕了;所以才出现与我们不期待的结果。

    修改方法:

    def sorryName():
        while(len(dinnersPerson) > 2):
            print('Sorry!!!'+dinnersPerson.pop()+',由于台风的原因,不能邀请你')
    

    相关文章

      网友评论

        本文标题:python中for循环和len函数的使用

        本文链接:https://www.haomeiwen.com/subject/ldojpftx.html