如何写出一见倾心的Python代码?

python基础

浏览数:253

2019-2-24

AD:资源代下载服务

见字如面,所谓一见倾心,可以理解为一次偶然的邂逅,眼神碰撞的的那几毫米,便在心里暗下誓言,从此便要与她(他)定下终身,之于python也是如此,在遇到它们之前,你觉得代码不过是if…else…而而,但恰逢那个午后,阳光透过窗户的缝隙洒进来,你抓耳挠腮,思而不得其所。望着满屏的def、class、毫无头绪,内心茫然又伴随小小的无奈,你开始焦躁,到底这个是应该是什么?鬼使神差的,你在命令行中敲出了import this。Python给你一段这样的文本

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
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.
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.
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!

翻译版:

Python之禅,作者Tim Peters

优美胜于丑陋
明了胜于晦涩
简单胜于复杂
复杂胜于杂乱
扁平胜于嵌套
间隔胜于紧凑
可读性很重要
特例不足以特殊到违背这些原则
不要忽视错误,除非程序需要这样做
面对模棱两可,拒绝猜测
解决问题最直接的方法应该有一种,最好只有一种
可能这种方法一开始不够直接,因为你不是范罗苏姆
做也许好过不做,但不想就做还不如不做
如果方案难以描述明白,那么一定是个糟糕的方案
如果容易描述,那么可能是个好方案
命名空间是一种绝妙的理念,多加利用

你内心窃喜,原来Python还有这样一个隐藏的密门。你开始揣摩并它的深意,接着你goole了这段文本的深意,认识到到pythonic这个词。从此便一发不可收拾:

以下

P 代表 pythonic

NP 代表 non-pythonic

链 式 表 达

NP

a = [u'凡', u'尘', u'皆', u'美']

if a.index(u'尘') < a.index(u'皆') and a.index(u'皆') < a.index(u'美'):
    print 'Yes'
else:
    print 'No'

>>> Yes

P

a = [u'凡', u'尘', u'皆', u'美']
if a.index(u'尘') < a.index(u'皆') < a.index(u'美'):
    print 'Yes'
else:
    print 'No'

>>> Yes

置 换 变 量

NP

a = u'凡尘皆美'
b = u'念念不忘'

temp = a
a = b
b = temp

>>> print a, b
>>> 念念不忘 凡尘皆美

P

a = u'凡尘皆美'
b = u'念念不忘'

a, b = b, a
>>> print a, b
>>> 念念不忘 凡尘皆美

迭 代 数 组

NP

arry = [u'凡', u'尘', u'皆', u'美']

for i in range(len(arry)):
    print i, arry[i]

>>>
0 凡
1 尘
2 皆
3 美

P

arry = [u'凡', u'尘', u'皆', u'美']

for i, j in enumerate(arry):
    print i, j

>>>
0 凡
1 尘
2 皆
3 美

字 符 拼 接

NP

chart_demo = u'凡尘皆美,念念不忘'

convert = chart_demo[0]
for i in chart_demo[1:]:
    convert += '_' + i

>>> print convert
>>> 凡_尘_皆_美_,_念_念_不_忘

P

chart_demo = u'凡尘皆美,念念不忘'

convert = '_'.join(chart_demo)

>>> print convert
>>> 凡_尘_皆_美_,_念_念_不_忘

列 表 生 成 式

NP

chart_demo = u'凡尘皆美,念念不忘'

result = []
for i in chart_demo:
    if i == u'念':
        result.append(i)

>>> print result
>>> ['念', '念']

P

chart_demo = u'凡尘皆美,念念不忘'

result = [i for i in chart_demo if i == u'念']

>>> print result
>>> ['念', '念']

布 尔 判 断

NP

a = u'凡'
b = [u'凡']
c =  {'fan': u'凡'}

if a != None and len(b) > 0 and c != {}:
    print '凡尘皆美'

>>> 凡尘皆美

P

a = u'凡'
b = [u'凡']
c =  {'fan': u'凡'}

if a and b and c:
    print '凡尘皆美'

>>> 凡尘皆美

zip 建 字 典

NP

keys = ['a', 'b', 'c', 'd']
values = [u'凡', u'尘', u'皆', u'美']

dict_result = {}
for i,j in enumerate(keys):
    dict_result[j] = values[i]

>>> print dict_result
>>> {'a': '凡', 'b': '尘', 'c': '皆', 'd': '美'}

P

keys = ['a', 'b', 'c', 'd']
values = [u'凡', u'尘', u'皆', u'美']

dict_result = dict(zip(keys, values))

>>> print dict_result
>>> {'a': '凡', 'b': '尘', 'c': '皆', 'd': '美'}

三 目 运 算 符

NP

chart_demo = u'凡尘皆美'

if len(chart_demo) > 3:
    temp = 'beautiful'
else:
    temp = 'ugly'

>>> print temp
>>> beautiful

P

chart_demo = u'凡尘皆美'

temp = 'beautiful' if len(chart_demo) > 3 else 'ugly'

>>> print temp
>>> beautiful

字 典 计 数

NP

chart_demo = u'凡尘皆美,念念不忘'

count = {}
for i in chart_demo:
    if not i in count:
        count[i] = 0
    count[i] += 1

>>> print count
>>> {'凡': 1, '尘': 1, '皆': 1, '美': 1, ',': 1, '念': 2, '不': 1, '忘': 1}

P

chart_demo = u'凡尘皆美,念念不忘'

No.1:
count = {}
for i in chart_demo:
    count[i] = count.get(i, 0) + 1

>>> print count
>>> {'凡': 1, '尘': 1, '皆': 1, '美': 1, ',': 1, '念': 2, '不': 1, '忘': 1}

No.2:
from collections import Counter
c = Counter(u'凡尘皆美,念念不忘')
>>> print c.most_common()
>>> [('念', 2), ('凡', 1), ('尘', 1), ('皆', 1), ('美', 1), (',', 1), ('不', 1), ('忘', 1)]

list 反 向 遍 历

NP

arry = [u'凡', u'尘', u'皆', u'美']

for i in range(len(arry) - 1, -1, -1):
    print arry[i]

>>>
美
皆
尘
凡

P

arry = [u'凡', u'尘', u'皆', u'美']

No.1:
for i in reversed(arry):
    print i

NO.2:
for i in arry[::-1]:
    print i

>>>
美
皆
尘
凡

for…else… 语 法

NP

chart_demo = u'凡尘皆美,念念不忘'

find = False
for i in chart_demo:
    if u',' == i:
        find = True
        break
if find:
    print '找到逗号'

>>> 找到逗号

P

chart_demo = u'凡尘皆美,念念不忘'

for i in chart_demo:
    if u',' == i:
        print '找到逗号'
        break
else:
    pass    

>>> 找到逗号

lambda 函 数

NP

chart_arry = [u'凡', u'尘', u'皆', u'美', u',', u'念', u'念', u'不', u'忘']

def count_bigger_five(arry):
    return 'Yes' if len(arry) > 5 else 'No'

>>> print count_bigger_five(chart_arry)
>>> Yes

P

chart_arry = [u'凡', u'尘', u'皆', u'美', u',', u'念', u'念', u'不', u'忘']

count_bigger_five2 = lambda x: 'Yes' if len(x) > 5 else 'No'
# 这里的x代表函数的参数,后面的式子直接是返回的结果

>>> print count_bigger_five2(chart_arry)
>>> Yes

map 函 数

NP

chart_arry = [u'凡', u'尘', u'皆', u'美']

chart_new = [x + u'+' for x in chart_arry]

>>> print chart_new
>>> ["凡+", "尘+", "皆+", "美+"]

P

chart_arry = [u'凡', u'尘', u'皆', u'美']

chart_new = map(lambda x:x + u'+', chart_arry)

>>> print chart_new
>>> ["凡+", "尘+", "皆+", "美+"]

filter 函 数

NP

chart_arry = [u'凡', u'尘', u'皆', u'美', u',', u'念', u'念', u'不', u'忘']

new_chart = []
for i in chart_arry:
    if i==u'念':
        new_chart.append(i)

>>> print new_chart
>>> ["念", "念"]

P

chart_arry = [u'凡', u'尘', u'皆', u'美', u',', u'念', u'念', u'不', u'忘']

new_chart = filter(lambda x: x if x==u'念' else None, chart_arry)

>>> print new_chart
>>> ["念", "念"]

reduce 函 数

NP

chart_arry = [u'凡', u'尘', u'皆', u'美', u',', u'念', u'念', u'不', u'忘']

chart_new = u'美句:'
for i in chart_arry:
    chart_new += i

>>> print s
>>> 美句:凡尘皆美,念念不忘

P

chart_arry = [u'凡', u'尘', u'皆', u'美', u',', u'念', u'念', u'不', u'忘']

chart_new = reduce(lambda x, y: x+y, chart_arry, u'美句:')

>>> print chart_new
>>> 美句:凡尘皆美,念念不忘

当然,pythonic还远不止此,欢迎小伙伴补充,此文章不断更新,欢迎收藏

对你有帮助的话,点赞加收藏吧。谢~

—update_v0.1_2018年01月31日20:33:20—

感谢@Silence 提供的另外一种list反向遍历写法

感谢@JerryYe 提供的字典计数中python标准库collections模块的用法

—update_v0.11_2018年02月01日09:46:28—

感谢@Henry 提醒的字 符 拼 接小节中错把convert写成covert的错误,已修正

—update_v0.21_2018年02月04日16:58:28—

感谢@Qanora 提供的链 式 表 达规则

更新了lambda,map,filter和reduce的使用,因为是讲NP和P,所以忽略了具体函数介绍,需要的小伙伴们,要自行查询文档哦。