欢迎访问我的网站,希望内容对您有用,感兴趣的可以加入免费知识星球。

让你的Python代码更加pythonic

Python基础 迷途小书童 4年前 (2019-12-08) 3161次浏览 0个评论

软硬件环境

  • windows 10 64bit
  • miniconda with python 3.7.1

Zen of Python

The Zen of PythonTim Peters(Python编程语言及其原始CPython实现的主要贡献者)提出的19行编写Python的指导原则,是Python开发者都应该反复阅读、理解、记忆以及运用的信条。 在2004年,成为了PEP 20 -- The Zen of Python。 在任何的Python版本中,你都可以打印出来。

import this

下面是网络上比较流行的中文翻译版本,来自赖勇浩,The Zen of Python译为python之禅

Beautiful is better than ugly.

优美胜于丑陋(Python 以编写优美的代码为目标)

Explicit is better than implicit.

明了胜于晦涩(优美的代码应当是明了的,命名规范,风格相似)

Simple is better than complex.

简洁胜于复杂(优美的代码应当是简洁的,不要有复杂的内部实现)

Complex is better than complicated.

复杂胜于凌乱(如果复杂不可避免,那代码间也不能有难懂的关系,要保持接口简洁)

Flat is better than nested.

扁平胜于嵌套(优美的代码应当是扁平的,不能有太多的嵌套)

Sparse is better than dense.

间隔胜于紧凑(优美的代码有适当的间隔,不要奢望一行代码解决问题)

Readability counts.

可读性很重要(优美的代码是可读的)

Special cases aren’t special enough to break the rules.

Although practicality beats purity.

即便假借特例的实用性之名,也不可违背这些规则(这些规则至高无上)

Errors should never pass silently.

Unless explicitly silenced.

不要包容所有错误,除非你确定需要这样做(精准地捕获异常,不写 except:pass 风格的代码)

In the face of ambiguity, refuse the temptation to guess.

当存在多种可能,不要尝试去猜测

There should be one– and preferably only one –obvious way to do it.

而是尽量找一种,最好是唯一一种明显的解决方案(如果不确定,就用穷举法)

Although that way may not be obvious at first unless you’re Dutch.

虽然这并不容易,因为你不是 Python 之父(这里的 Dutch 是指 Guido )

Now is better than never.

Although never is often better than right now.

做也许好过不做,但不假思索就动手还不如不做(动手之前要细思量)

If the implementation is hard to explain, it’s a bad idea.

If the implementation is easy to explain, it may be a good idea.

如果你无法向人描述你的方案,那肯定不是一个好方案;反之亦然(方案测评标准)

Namespaces are one honking great idea — let’s do more of those!

命名空间是一种绝妙的理念,我们应当多加利用(倡导与号召)

还有一个词叫pythonic,意思是非常python,也就是说编写的代码非常符合python的设计哲学,优雅、地道、整洁。

要想写出pythonic的代码,需要经常练习,观察学习大牛的代码,然后应用到自己的工程中。以下是一些常见的pythonic代码片段。

交换两个变量的值

如果要互换两个变量的值,一般的写法是这样的:

temp = a
a = b
b = temp

更加优雅的写法:

a, b = b, a

链式比较

如下的写法应该是比较常见的,中间有好几个and

a = 3
b = 1   

b >= 1 and b <= a and a < 10 #True

其实,还有更简洁明了的写法

a = 3
b = 1 

1 <= b <= a < 10  #True

真值测试

编码中判断真值是常见的操作

name = 'Tim'
langs = ['AS3', 'Lua', 'C']
info = {'name': 'Tim', 'sex': 'Male', 'age':23 }

if name != '' and len(langs) > 0 and info != {}:
    print('All True!') #All True!

python对于任意对象,可以直接判断其真假,无需写判断条件,这样既能保证正确性,又能减少代码量。关键字not是取反的意思。

name = 'Tim'
langs = ['AS3', 'Lua', 'C']
info = {'name': 'Tim', 'sex': 'Male', 'age':23 }    

if name and langs and info:
    print('All True!')  #All True!

字符串反转

如果按照C的思路,应该是这样写的

def reverse_str( s ):
    t = ''
    for x in range(len(s)-1,-1,-1):
        t += s[x]
    return t

python中有更简单、更高效的写法

def reverse_str( s ):
    return s[::-1]  

如果是检测回文,就是一句话input == input[::-1],多么的优雅!

字符串列表的连接

一般的写法是这样的

strList = ["Python", "is", "good"]  
res = ''
for s in strList:
    res += s + ' '
#Python is good 
#最后还有个多余空格

string.join()常用于连接列表里的字符串,相对而言,这种方式十分高效,且不会犯错。

strList = ["Python", "is", "good"]  

res =  ' '.join(strList) #Python is good

打开/关闭文件

执行文件操作时,最后一定不能忘记的操作是关闭文件,即使报错了也要close。普通的方式是在finnally块中显式的调用close方法。

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

使用with语句,系统会在执行完文件操作后自动关闭文件对象,如下的写法更安全,更简洁

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

打断无限循环

python并不像C语言有do/while语句,它只有一个whilefor循环语句,有时你并不会提前知道什么时候循环会结束,或者你需要打破循环。一个不能再普通的例子就是正在按行迭代一个文件内容:

file = open("some_filename", "r")

while 1:   # infinite loop
    line = file.readline()
    if not line:  # 'readline()' returns None at end of file.
        break

    # Process the line.

这样做并不聪明,但是足够规范。对于文件来说还有一个更漂亮的做法:

file = open("some_filename", "r")

for line in file:
    # Process the line.

注意python中也有一个continue语句(就像C中的)来跳过本次循环进入下一次循环。

数组的迭代

pythonfor语句并不和C语言的一样,更像其他语言的foreach. 如果你需要在迭代中使用索引,标准的做法是:

array = [1, 2, 3, 4, 5]

for i in range(len(array)):
    # Do something with 'i'.

这是相当笨拙的,更干净简洁的做法是:

array = [1, 2, 3, 4, 5]

for i, e in enumerate(array):
    # Do something with index 'i' and its corresponding element 'e'.

列表生成器

这是python中全新的一个特征,来源于函数式编程语言Haskell(很酷的编程语言,顺便告诉你,你应该看看Haskell)

其思想是:有时你想要为具有某些特征的对象做一个链表,比如你想要为020的偶数做一个链表:

results = []
for i in range(20):
    if i % 2 == 0:
        results.append(i)

results里面就是结果:[0, 2, 4, 6, 8, 10, 12, 14, 16, 18](没有20,因为range(20)是从019)。但是同样的事情你可以用列表生成式来做地更简洁些:

results = [x for x in range(20) if x % 2 == 0]

列表生成式是循环的语法糖。你可以做些更复杂的:

results = [(x, y)
           for x in range(10)
           for y in range(10)
           if x + y == 5
           if x > y]

结果results[(3, 2), (4, 1), (5, 0)]。 所以你可以在方括号中写任意多个forif语句, 你可以用列表生成式来实现快速排序算法:

def quicksort(lst):
    if len(lst) == 0:
        return []
    else:
        return quicksort([x for x in lst[1:] if x < lst[0]]) + [lst[0]] + quicksort([x for x in lst[1:] if x >= lst[0]])

优美吗? :-)

参考资料

喜欢 (0)

您必须 登录 才能发表评论!