欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

15个Pythonic的代码示例(值得收藏)

程序员文章站 2022-06-22 11:42:29
python由于语言的简洁性,让我们以人类思考的方式来写代码,新手更容易上手,老鸟更爱不释手。要写出 pythonic(优雅的、地道的、整洁的)代码,还要平时多观察那些大牛代码,github 上有很多...

python由于语言的简洁性,让我们以人类思考的方式来写代码,新手更容易上手,老鸟更爱不释手。

要写出 pythonic(优雅的、地道的、整洁的)代码,还要平时多观察那些大牛代码,github 上有很多非常优秀的源代码值得阅读,比如:requests、flask、tornado,这里小明收集了一些常见的 pythonic 写法,帮助你养成写优秀代码的习惯。

01. 变量交换

bad

tmp = a
a = b
b = tmp

pythonic

a,b = b,a

02. 列表推导

bad

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

pythonic

my_list = [i*2 for i in range(10)]

03. 单行表达式

虽然列表推导式由于其简洁性及表达性,被广受推崇。

但是有许多可以写成单行的表达式,并不是好的做法。

bad

print 'one'; print 'two'

if x == 1: print 'one'

if <complex comparison> and <other complex comparison>:
  # do something

pythonic

print 'one'
print 'two'

if x == 1:
  print 'one'

cond1 = <complex comparison>
cond2 = <other complex comparison>
if cond1 and cond2:
  # do something

04. 带索引遍历

bad

for i in range(len(my_list)):
  print(i, "-->", my_list[i])

pythonic

for i,item in enumerate(my_list):
  print(i, "-->",item)

05. 序列解包

pythonic

a, *rest = [1, 2, 3]
# a = 1, rest = [2, 3]

a, *middle, c = [1, 2, 3, 4]
# a = 1, middle = [2, 3], c = 4

06. 字符串拼接

bad

letters = ['s', 'p', 'a', 'm']
s=""
for let in letters:
  s += let

pythonic

letters = ['s', 'p', 'a', 'm']
word = ''.join(letters)

07. 真假判断

bad

if attr == true:
  print 'true!'

if attr == none:
  print 'attr is none!'

pythonic

if attr:
  print 'attr is truthy!'

if not attr:
  print 'attr is falsey!'

if attr is none:
  print 'attr is none!'

08. 访问字典元素

bad

d = {'hello': 'world'}
if d.has_key('hello'):
  print d['hello']  # prints 'world'
else:
  print 'default_value'

pythonic

d = {'hello': 'world'}

print d.get('hello', 'default_value') # prints 'world'
print d.get('thingy', 'default_value') # prints 'default_value'

# or:
if 'hello' in d:
  print d['hello']

09. 操作列表

bad

a = [3, 4, 5]
b = []
for i in a:
  if i > 4:
    b.append(i)

pythonic

a = [3, 4, 5]
b = [i for i in a if i > 4]
# or:
b = filter(lambda x: x > 4, a)

bad

a = [3, 4, 5]
for i in range(len(a)):
  a[i] += 3

pythonic

a = [3, 4, 5]
a = [i + 3 for i in a]
# or:
a = map(lambda i: i + 3, a)

10. 文件读取

bad

f = open('file.txt')
a = f.read()
print a
f.close() 

pythonic

with open('file.txt') as f:
  for line in f:
    print line 

11. 代码续行

bad

my_very_big_string = """for a long time i used to go to bed early. sometimes, \
  when i had put out my candle, my eyes would close so quickly that i had not even \
  time to say “i'm going to sleep.”"""

from some.deep.module.inside.a.module import a_nice_function, another_nice_function, \
  yet_another_nice_function 

pythonic

my_very_big_string = (
  "for a long time i used to go to bed early. sometimes, "
  "when i had put out my candle, my eyes would close so quickly "
  "that i had not even time to say “i'm going to sleep.”"
)

from some.deep.module.inside.a.module import (
  a_nice_function, another_nice_function, yet_another_nice_function) 

12. 显式代码

bad

def make_complex(*args):
  x, y = args
  return dict(**locals())

pythonic

def make_complex(x, y):
  return {'x': x, 'y': y}

13. 使用占位符

pythonic

filename = 'foobar.txt'
basename, _, ext = filename.rpartition('.')

14. 链式比较

bad

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

pythonic

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

理解了链式比较操作,那么你应该知道为什么下面这行代码输出的结果是 false

>>> false == false == true 
false

15. 三目运算

这个保留意见。随使用习惯就好。

bad

if a > 2:
  b = 2
else:
  b = 1
#b = 2

pythonic

a = 3  

b = 2 if a > 2 else 1
#b = 2 

参考文档


到此这篇关于15个pythonic的代码示例(值得收藏)的文章就介绍到这了,更多相关pythonic代码内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关标签: Pythonic