有趣的Pythonic写法

Python 这门编程语言最大的特点就是简单易用。本文列举一些典型的 Pythonic (优雅、地道、简洁)写法。

变量替换

普通写法

a = 10
b = 20
tmp = a
a = b
b = tmp

pythonic

a, b = b, a

遍历区间元素

比如打印 1 3 5 7 9

其他语言,如 Java:

for (int i = 1; i < 10; i += 2)
System.out.print(i + " ");

pythonic

for i in range(1, 10, 2)
print i,

带有索引位置的列表遍历

weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
for i in range(len(weekdays)):
print i, '---->', weekdays[i]

pythonic

for i, weekday in enumerate(weekdays):
print i, '---->', weekday

字符串连接

weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
s = weekdays[0]
for weekday in weekdays[1:]:
s += ', ' + weekday
print s

pythonic

print(', '.join(weekdays))

打开/关闭文件

打开文件最后一定要关闭文件。普通的方法是在finally语句中关闭。

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

pythonic

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

使用 with open 语句,系统会在执行完文件操作后自动关闭文件对象。

列表推导式

如要生成一个 [0, 3, 6, 9, 12] 这样的列表

ls = []
for i in range(5):
ls.append(i*3)

pythonic

[i*3 for i in range(5)]

序列解包

lbd = 'lbd', 'male', '25', 'beijing'
name = lbd[0]
gender = lbd[1]
age = lbd[2]
location = lbd[3]

pythonic

name, gender, age, location = lbd

遍历字典的 key 和 value

for k in d:
print (k, '---->', d[k])

pythonic

for k, v in d.items():
print(k, '---->', v)

if/else

if x == y:
return 0
else:
return 1

pythonic

return 0 if x == y else 1

相当于 return x==y ? 0 : 1

字符串格式化

s1 = 'lbd'
s2 = 25
s3 = 'my name is %s and i am %d years old' % (s1, s2)

pythonic

s3 = 'my name is {name} and i am {age} years old'.format(name = 'lbd', age = 25)

列表切片

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)

pythonic

#子区间
sub_items = items[1:4]
#奇数
odd_items = items[1::2]
#拷贝
copy_items = items[:] or items[::]

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

--------------------------
| P | y | t | h | o | n |
--------------------------
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
--------------------------

获取字典元素

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

pythonic

print (d.get('name', 'unknown'))

预设字典默认值

当字典 value 为列表时,需要判断 key 是否在字典中。

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]

pythonic

groups = {}
for (key, value) in data:
groups.setdefault(key, []).append(value)

字典推导式

numbers = [1, 2, 3]
d = dict([(number, number*2) for number in numbers])

pythonic

d = {number:number*2 for number in numbers}
# 还可以加过滤条件
d = {number:number*2 for number in numbers if number > 1}

参考

博文:《代码这样写不止于优雅(Python版)》

欢迎关注公众号: FullStackPlan 获取更多干货

Copyright © 2016 - 2017 LBD's Blog All Rights Reserved.

访客数 : | 访问量 :