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

Python017

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

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

同时,要让代码写得简洁,你也得熟悉Python本身,充分挖掘其能力。Python内建的几个高阶函数:map,reduce,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

Python基础

数组排序算法

2. 私信发送“ 资料 ”, 即可获取

(私信方法:点我主页头像旁边的私信按钮,回复“资料”即可)

使用Tkinter图形库,如果你是用的linux系统 记得将第一行改为from tkinter import *

这个代码实现的挺简单,并不是很复杂的科学计算器界面,你可以以此为基础,添加自己想要的东西:给你个截图:

代码是如下, 我就不给你添注释了啊:

#!/usr/bin/env python3.4

from Tkinter import *

import parser

root = Tk()

root.title('Calculator')

i = 0

def factorial():

"""Calculates the factorial of the number entered."""

whole_string = display.get()

number = int(whole_string)

fact = 1

counter = number

try:

while counter >0:

fact = fact*counter

counter -= 1

clear_all()

display.insert(0, fact)

except Exception:

clear_all()

display.insert(0, "Error")

def clear_all():

"""clears all the content in the Entry widget"""

display.delete(0, END)

def get_variables(num):

"""Gets the user input for operands and puts it inside the entry widget"""

global i

display.insert(i, num)

i += 1

def get_operation(operator):

"""Gets the operand the user wants to apply on the functions"""

global i

length = len(operator)

display.insert(i, operator)

i += length

def undo():

"""removes the last entered operator/variable from entry widget"""

whole_string = display.get()

if len(whole_string):## repeats until

## now just decrement the string by one index

new_string = whole_string[:-1]

print(new_string)

clear_all()

display.insert(0, new_string)

else:

clear_all()

display.insert(0, "Error, press AC")

def calculate():

"""

Evaluates the expression

ref : http://stackoverflow.com/questions/594266/equation-parsing-in-python

"""

whole_string = display.get()

try:

formulae = parser.expr(whole_string).compile()

result = eval(formulae)

clear_all()

display.insert(0, result)

except Exception:

clear_all()

display.insert(0, "Error!")

root.columnconfigure(0,pad=3)

root.columnconfigure(1,pad=3)

root.columnconfigure(2,pad=3)

root.columnconfigure(3,pad=3)

root.columnconfigure(4,pad=3)

root.rowconfigure(0,pad=3)

root.rowconfigure(1,pad=3)

root.rowconfigure(2,pad=3)

root.rowconfigure(3,pad=3)

display = Entry(root, font = ("Calibri", 13))

display.grid(row = 1, columnspan = 6, sticky = W+E)

one = Button(root, text = "1", command = lambda : get_variables(1), font=("Calibri", 12))

one.grid(row = 2, column = 0)

two = Button(root, text = "2", command = lambda : get_variables(2), font=("Calibri", 12))

two.grid(row = 2, column = 1)

three = Button(root, text = "3", command = lambda : get_variables(3), font=("Calibri", 12))

three.grid(row = 2, column = 2)

four = Button(root, text = "4", command = lambda : get_variables(4), font=("Calibri", 12))

four.grid(row = 3 , column = 0)

five = Button(root, text = "5", command = lambda : get_variables(5), font=("Calibri", 12))

five.grid(row = 3, column = 1)

six = Button(root, text = "6", command = lambda : get_variables(6), font=("Calibri", 12))

six.grid(row = 3, column = 2)

seven = Button(root, text = "7", command = lambda : get_variables(7), font=("Calibri", 12))

seven.grid(row = 4, column = 0)

eight = Button(root, text = "8", command = lambda : get_variables(8), font=("Calibri", 12))

eight.grid(row = 4, column = 1)

nine = Button(root , text = "9", command = lambda : get_variables(9), font=("Calibri", 12))

nine.grid(row = 4, column = 2)

cls = Button(root, text = "AC", command = clear_all, font=("Calibri", 12), foreground = "red")

cls.grid(row = 5, column = 0)

zero = Button(root, text = "0", command = lambda : get_variables(0), font=("Calibri", 12))

zero.grid(row = 5, column = 1)

result = Button(root, text = "=", command = calculate, font=("Calibri", 12), foreground = "red")

result.grid(row = 5, column = 2)

plus = Button(root, text = "+", command = lambda : get_operation("+"), font=("Calibri", 12))

plus.grid(row = 2, column = 3)

minus = Button(root, text = "-", command = lambda : get_operation("-"), font=("Calibri", 12))

minus.grid(row = 3, column = 3)

multiply = Button(root,text = "*", command = lambda : get_operation("*"), font=("Calibri", 12))

multiply.grid(row = 4, column = 3)

divide = Button(root, text = "/", command = lambda : get_operation("/"), font=("Calibri", 12))

divide.grid(row = 5, column = 3)

# adding new operations

pi = Button(root, text = "pi", command = lambda: get_operation("*3.14"), font =("Calibri", 12))

pi.grid(row = 2, column = 4)

modulo = Button(root, text = "%", command = lambda : get_operation("%"), font=("Calibri", 12))

modulo.grid(row = 3, column = 4)

left_bracket = Button(root, text = "(", command = lambda: get_operation("("), font =("Calibri", 12))

left_bracket.grid(row = 4, column = 4)

exp = Button(root, text = "exp", command = lambda: get_operation("**"), font = ("Calibri", 10))

exp.grid(row = 5, column = 4)

## To be added :

# sin, cos, log, ln

undo_button = Button(root, text = "<-", command = undo, font =("Calibri", 12), foreground = "red")

undo_button.grid(row = 2, column = 5)

fact = Button(root, text = "x!", command = factorial, font=("Calibri", 12))

fact.grid(row = 3, column = 5)

right_bracket = Button(root, text = ")", command = lambda: get_operation(")"), font =("Calibri", 12))

right_bracket.grid(row = 4, column = 5)

square = Button(root, text = "^2", command = lambda: get_operation("**2"), font = ("Calibri", 10))

square.grid(row = 5, column = 5)

root.mainloop()