for else 是 Python 中特有的语法格局,else 中的代码在 for 轮回遍历完所有元素之后履行。
- flagfound = False
- for i in mylist:
- if i == theflag:
- flagfound = True
- break
- process(i)
- if not flagfound:
- raise ValueError("List argument missing terminal flag.")
pythonic
4、for/else语句
- for i in mylist:
- if i == theflag:
- break
- process(i)
- else:
- raise ValueError("List argument missing terminal flag.")
5、字符串格局化
- s1 = "foofish.net"
- s2 = "vttalk"
- s3 = "welcome to %s and following %s" % (s1, s2)
pythonic
- s3 = "welcome to {blog} and following {wechat}".format(blog="foofish.net", wechat="vttalk")
很难说用 format 比用 %s 的代码量少,然则 format 更易于懂得。
“Explicit is better than implicit — Zen of Python”
获取列表中的部分元素最先想到的就是用 for 轮回根据前提提取元素,这也是其它说话中惯用的手段,而在 Python 中还有强大年夜的切片功能。
- items = range(10)
- # 奇数
- odd_items = []
- for i in items:
- if i % 2 != 0:
- odd_items.append(i)
- # 拷贝
- copy_items = []
- for i in items:
推荐阅读
强调单路性能/定位数据中心应用,AMD正式推出面向数据中心的处理器EPYC
【51CTO.com原创稿件】在办事器处理器范畴,英特尔绝对是一家独大年夜,无人能比。90%以上的市场占领率,也充>>>详细阅读
本文标题:代码这样写不止于优雅(Python 版)
地址:http://www.17bianji.com/lsqh/35900.html
1/2 1

网友点评
精彩导读
科技快报
品牌展示