python 不一样的写法
转自:https://www.cnblogs.com/wrxblog/p/9734053.html
python 不一样的写法
打印index
对于一个列表,或者说一个序列我们经常需要打印它的index,一般传统的做法或者说比较low的写法:

更优雅的写法是多用enumerate

两个序列的循环
我们会经常对两个序列进行计算或者处理,比较low的方法是用下标去循环处理

更优雅一点的方法:用zip轻松搞定

有没有更优雅的方法呢,比如如果两个序列有10000的长度,当然有的用izip

当然izip还是Py2.x时代的产物,现在Py3.6里面默认zip都是izip了!
交换变量
多个变量之间的交换,相信很多有c,c++语言基础的同学对这个再熟悉不过了,比如我们经典的冒泡排序,就会用这一招,看看比较传统的做法:

更优雅的做法是:

字典的读取
字典是我们经常使用的数据结构,对于字典的访问和读取,如果我们的读取的字典的key为空怎么办,一般我们需要一个缺省值,菜鸟的写法:

比较优雅的做法是:

巧妙的利用了字典get的用法,如果字典里面没有Susan这个key,则用unknow来表示缺省值!
循环查找
我们经常会在一个大的循环中作搜索业务,比如从一个文件中搜索关键字,比如从文件名列表中查找一些特殊的文件名,想当然的写法如下:

更优雅的写法:上面的写法是传统的c,c++写法,Python里面有更简洁的写法:

文件读取查找
通常来说,我们要打开一个文件,然后对文件的内容进行循环读取和处理,菜鸟的写法如下:

更优雅的写法:

关于锁的写法
对于并发操作尤其是多线程的操作,我们对同一块内存进行读写操作的时候,通常我们都加锁保护的,想当然的写法如下:

上面这样的写法我自己写了很多年,觉得没有啥问题啊,后来遇到下面的写法,瞬间膜拜了!
更优雅的写法:
