设为首页 加入收藏

TOP

循环优化一
2023-07-25 21:26:47 】 浏览:22
Tags:

主角:takewhile

  判断序列中元素是否为偶数,奇数则终止

这是我们最常用的一种方式,其实没必要这么复杂

 1 a = [4, 6, 7, 3]
 2 
 3 
 4 def judge_is_even(item):
 5     if item % 2 == 0:
 6         return True
 7     return False
 8 
 9 
10 # 最常用
11 for item in a:
12     if not judge_is_even(item):
13         break
14     print(item)

优化后:

 1 from itertools import takewhile
 2 
 3 a = [4, 6, 7, 3]
 4 
 5 
 6 def judge_is_even(item):
 7     if item % 2 == 0:
 8         return True
 9     return False
10 
11 
12 for item in takewhile(judge_is_even, a):
13     print(item)

其原理为:遍历第二个可迭代对象,当前值调用第一个入参,并对返回的结果进行真值测试,True继续,False终止

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇迭代器执行切片 下一篇Python:灵活的开发环境

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目