Python_内置

2018-08-07  本文已影响0人  违规昵称不予展示

1.enumerate() 返回索引和内容

cities = ['shanghai', 'beijing', 'shenzhen', 'chengdu']
i = 0
for c in cities:
    print i+1, '-->', c
    i += 1
1 --> shanghai
2 --> beijing
3 --> shenzhen
4 --> chengdu

可以改写为

>>> for i,city in enumerate(cities):
...     print i+1, '-->', c
...
1 --> chengdu
2 --> chengdu
3 --> chengdu
4 --> chengdu

2.zip() 两个列表一一对应时用的

>>> names = ['leo', 'jack', 'john', 'james']
>>> colors = ['red', 'green', 'blue', 'yellow']
>>> n = min(len(names), len(colors))
>>> for i in range(n):
...     print names[i], '-->', colors[i]
...
leo --> red
jack --> green
john --> blue
james --> yellow

改写为

>>> for name, color in zip(names, colors):
...     print name, '-->', color
...
leo --> red
jack --> green
john --> blue
james --> yellow

如果两个序列有10000000的长度,当然用izip

import itertools
>>> for name, color in itertools.izip(names, colors):
...     print name, '-->', color
...
leo --> red
jack --> green
john --> blue
james --> yellow

现在py3.6中默认zip为izip

3. 变量交换

多个变量之间的交换,相信很多有c,c++语言基础的同学对这个再熟悉不过了,比如我们经典的冒泡排序,就会用这一招,看看比较传统的做法:

>>> x = 1
>>> y = 2
>>> print '>>before:x={},y={}'.format(x,y)
>>> tmp=y
>>> y=x
>>> x=tmp
>>> print '>>after:x={},y={}'.format(x,y)


>>before:x=1,y=2
>>after:x=2,y=1

更优雅的做法是:

>>> x=1
>>> y=2
>>> print '>>before:x={},y={}'.format(x,y)
>>> x,y = y,x
>>> print '>>after:x={},y={}'.format(x,y)


>>before:x=1,y=2
>>after:x=2,y=1

4.读取字典

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

>>> students = {'Lili': 18, 'Sam': 25}
>>> if 'Susan' in students:
...     student = students['Susan']
... else:
...     student = 'unknow'
...
>>> print 'Susan is {} years old'.format(student)
Susan is unknow years old

大佬的写法是:

>>> student = students.get('Susan','unknow')
>>> print 'Susan is {} years old'.format(student)
Susan is unknow years old

5.循环查找

我们经常会在一个大的循环中作搜索业务,比如从一个文件中搜索关键字,比如从文件名列表中查找一些特殊的文件名,想当然的写法如下

>>> target_letter = 'd'
>>> letters = ['a', 'b', 'c']
>>> found = False
>>> for letter in letters:
...     if letter == target_letter:
...         print 'Found'
...         found = True
...         break
...
>>> if not found:
...     print 'Not found'
...
Not found

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

>>> for letter in letters:
...     if letter == target_letter:
...         print 'Found'
...         break
... else:
...     print 'Not found'
...
Not found

6.文件读取

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

>>> f = open('data.txt')
>>> try:
...     text = f.read()
...     for line in text.split('\n'):
...         print line
... finally:
...     f.close()
...
hello
world

更优雅的写法:

>>> with open('data.txt')as f:
...     for line in f:
...         print line.strip('\n')
...
hello
world

7.关于锁的写法

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

>>> import threading
>>> lock = threading.Lock()
>>> lock.acquire()
True
>>> try:
...     print 'Citical part,do something...'
... finally:
...     lock.release()
...
Citical part,do something...

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

>>> lock = threading.Lock()
>>> with lock:
...     print 'Citical part,do somethin...'
...
Citical part,do somethin...
上一篇下一篇

猜你喜欢

热点阅读