06月28, 2017

python优雅编程

链式比较操作

old

age = 18
if age > 18 and age < 60:
    print("young man")

new

if 18 < age < 60:
    print("young man")

if/else 三目运算

old

if gender == 'male':
    text = '男'
else:
    text = '女'

new

text = '男' if gender == 'male' else '女'

真值判断

old

if attr == True:
    do_something()

if len(values) != 0: # 判断列表是否为空
    do_something()

new

if attr:
    do_something()

if values:
    do_something()

for/else语句

old

flagfound = False
for i in mylist:
    if i == theflag:
        flagfound = True
        break
    process(i)

if not flagfound:
    raise ValueError("List argument missing terminal flag.")

new

for i in mylist:
    if i == theflag:
        break
    process(i)
else:
    raise ValueError("List argument missing terminal flag.")

字符串格式化

old

s1 = "foofish.net"
s2 = "vttalk"
s3 = "welcome to %s and following %s" % (s1, s2)

new

s3 = "welcome to {blog} and following {wechat}".format(blog="foofish.net", wechat="vttalk")

列表切片

列表元素的下标不仅可以用正数表示,还是用负数表示,最后一个元素的位置是 -1,从右往左,依次递减。 old

items = range(10)

# 奇数
odd_items = []
for i in items:
    if i % 2 != 0:
        odd_items.append(i)

# 拷贝
copy_items = []
for i in items:
    copy_items.append(i)

new

# 第1到第4个元素的范围区间
sub_items = items[1:4]
# 奇数
odd_items = items[1::2]
#拷贝
copy_items = items[::] 或者 items[:]

善用生成器

生成器的好处就是无需一次性把所有元素加载到内存,只有迭代获取元素时才返回该元素,而列表是预先一次性把全部元素加载到了内存。 old

def fib(n):
    a, b = 0, 1
    result = []
     while b < n:
        result.append(b)
        a, b = b, a+b
    return result

new

def fib(n):
    a, b = 0, 1
    while a < n:
        yield a
        a, b = b, a + b

获取字典元素

old

d = {'name': 'foo'}
if d.has_key('name'):
    print(d['name'])
else:
    print('unknown')

new

d.get("name", "unknown")

预设字典默认值

old

data = [('foo', 10), ('bar', 20), ('foo', 39), ('bar', 49)]
groups = {}
for (key, value) in data:
    if key in groups:
        groups[key].append(value)
    else:
        groups[key] = [value]

new

# 第一种方式
groups = {}
for (key, value) in data:
    groups.setdefault(key, []).append(value) 

# 第二种方式
from collections import defaultdict
groups = defaultdict(list)
for (key, value) in data:
    groups[key].append(value)

字典推导式

old

numbers = [1,2,3]
my_dict = dict([(number,number*2) for number in numbers])
print(my_dict)  # {1: 2, 2: 4, 3: 6}

new

numbers = [1, 2, 3]
my_dict = {number: number * 2 for number in numbers}
print(my_dict)  # {1: 2, 2: 4, 3: 6}

# 还可以指定过滤条件
my_dict = {number: number * 2 for number in numbers if number > 1}
print(my_dict)  # {2: 4, 3: 6}

遍历字典的 key 和 value

old

# 方法一:速度没那么快,因为每次迭代的时候还要重新进行hash查找 key 对应的 value
for k in d:
    print (k, '--->', d[k])

# 方法二:遇到字典非常大的时候,会导致内存的消耗增加一倍以上
for k, v in d.items():
    print (k, '--->', v)

new

# python3只有 items 方法,等值于 iteritems
for k, v in d.iteritems():
    print (k, '--->', v)

序列解包

old

p = 'vttalk', 'female', 30, 'python@qq.com'

name = p[0]
gender = p[1]
age = p[2]
email = p[3]

new

name, gender, age, email = p

合理使用列表

列表对象(list)是一个查询效率高于更新操作的数据结构,比如删除一个元素和插入一个元素时执行效率就非常低,因为还要对剩下的元素进行移动 old

names = ['raymond', 'rachel', 'matthew', 'roger',
         'betty', 'melissa', 'judith', 'charlie']
names.pop(0)
names.insert(0, 'mark')

new

# deque 是一个双向队列的数据结构,删除元素和插入元素会很快
from collections import deque
names = deque(['raymond', 'rachel', 'matthew', 'roger',
               'betty', 'melissa', 'judith', 'charlie'])
names.popleft()
names.appendleft('mark')

列表推导式

生成器表达式、字典推导式 old

result = []
for i in range(10):
    s = i*2
    result.append(s)

new

[i*2 for i in xrange(10)]

打开/关闭文件

old

f = open('data.txt')
try:
    data = f.read()
finally:
    f.close()

new

with open('data.txt') as f:
    data = f.read()

带有索引位置的集合遍历

old

colors = ['red', 'green', 'blue', 'yellow']

for i in range(len(colors)):
    print (i, '--->', colors[i])

new

for i, color in enumerate(colors):
    print (i, '--->', color)

循环遍历区间元素

xrange 返回的是生成器对象,生成器比列表更加节省内存,不过需要注意的是 xrange 是 python2 中的写法,python3 只有 range 方法,特点和 xrange 是一样的。 old

for i in [0, 1, 2, 3, 4, 5]:
    (print i)
# 或者
for i in range(6):
    (print i)

new

for i in xrange(6):
    (print i)

变量交换

old

a = 1
b = 2
tmp = a
a = b
b = tmp

new

a, b = b, a

本文链接:https://blog.jnliok.com/post/python-coding-best.html

-- EOF --

Comments