求简洁优美的python代码例子、片段、参考资料

发布网友 发布时间:2022-04-20 10:32

我来回答

4个回答

热心网友 时间:2022-04-07 13:08

  建议你去看一本书:《计算机程序的构造与解释》。里面用的语言是Scheme,一种Lisp的方言。通过这本书学习程序的抽象、封装,以及重要的函数式编程思想。等看完这本书以后,你在来写写Python代码,就知道如何让其简洁直观而又不失其可读性了。

  同时,要让代码写得简洁,你也得熟悉Python本身,充分挖掘其能力。Python内建的几个高阶函数:map,rece,filter,enumerate等等,lambda表达式,zip函数,以及标准库里强大的itertools、functools模块,都是函数式编程的利器。此外Python本身提供了许多非常好的语法糖衣,例如装饰器、生成器、*args和**kwargs参数、列表推导等等,也是简化代码的有效手段。还有,Python有着强大的库。多参考官方的文档了解其原理和细节,我相信你也能写出高效简洁的代码的。

  其实代码的简洁没有什么捷径,它要求你了解你要解决的问题,所使用的语言和工具,相关的算法或流程。这些都得靠你自己不断地练习和持续改进代码,不断地专研问题和学习知识。加油吧,少年!

  楼下让你参考PEP 20,其实不用去查,标准库里的this模块就是它(试试import this):The Zen of Python(Python之禅)。它就是一段话:

s='''
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!
'''

  让我们来做个小游戏吧:统计上面这段话的单词总数目,以及各个单词的数量(不区分大小写),然后按字典顺序输出每个单词出现的次数。要求,例如it's和you're等要拆分成it is和you are。你会怎么写代码呢?如何保持简洁呢?

  下面是我的参*,争取比我写的更简洁吧~

import re

p = re.compile("(\w+)('s|'re|n't)?")
wc = {}
tail_map = { "'s" : 'is', "'re" : 'are', "n't": 'not'}

for m in re.finditer(p, s):
    word = m.group(1).lower()                   # Get the word in lower case
    wc[word] = wc.get(word, 0) + 1              # Increase word count
    tail = m.group(2)                           # Get the word tail
    if tail is not None:                        # If a word tail exists,
        tail = tail_map[tail]                   # map it to its full form
        wc[tail] = wc.get(tail, 0)+1            # Increase word count

print ('Total word count: %d'%sum(wc.values())) # Output the total count
max_len = max(map(len, wc.keys()))              # Calculate the max length of words for pretty printing
for w in sorted(wc.keys()):                     # Sort the words
    print ('%*s => %d'%(max_len, w, wc[w]))     # Output

热心网友 时间:2022-04-07 14:26

楼主贴的那段代码好像是我写的那段吧,我来告诉你如何写出来的吧

首先我不是高手,我也没有人教,我的编程都是自学的,我只是一个业余爱好者.

写出这样的代码很简单,就是要多练,我只是把python的基本语法学会,然后就不停地练习,我没有看过楼上的那些资料,我只是不停地码代码,或许有捷径,但是我没有发现.

我从07年开始写python的脚本,我一开始的代码风格也很差,特别是我先学c++,然后再转python的,当写的代码越来越多,对python的了解就会加深,代码风格也会自动改变的,不需要着急,其实这就是对一门语言的了解程度,你可以看看我回答的问题,我的回答就是我对python的理解,如果你能坚持下来,相信7年后你写的代码会比我写得更好.



楼上的题目有点意思,我也写一下,不知道对否

s='''
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!
'''

import re ,collections
tail_map = { "'s" : ' is', "'re" : ' are', "n't": ' not' }
data = collections.Counter( re.findall( '\w+' ,re.sub( "('s|'re|n't)" ,lambda matchobj : tail_map[ matchobj.group( ) ] ,s.lower( ) ) ) )

max_len = max( data.values( ) )
print( 'Total word count : %d' ,sum( data.values( ) ) )

for word in sorted( data ):
     print ( '%*s => %d' % ( max_len, word, data[ word ] ) )

热心网友 时间:2022-04-07 16:01

参考PEP 20

热心网友 时间:2022-04-07 17:52

流畅的python
声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。
E-MAIL:11247931@qq.com