简单,美,唯一的方法.实现易于解释.
举例1:
def quicksort(array):
less=[]; greater=[]
if len(array) <= 1:
return array
pivot = array.pop()
for x in array:
if x <= pivot: less.append(x)
else: greater.append(x)
return quicksort(less) + [pivot] + quicksort(greater)
举例2:
a,b = b,a
举例3:
for i in alist:
do_sth_with(i)
举例4:
with open(path,'r') as f:
do_sth_with(f)
举例5:
a = [1,2,3,4]
c = "abcdef"
print a[::-1]
print c[::-1]
print list(reversed(a))
print list(reversed(c))
举例6:
print 'Hello %s!" %("Tom",)
%s是非常影响可读性的,因为数量多了以后,很难清楚哪一个占位符对应那应该实参.所以相对应的Pythonic代码是这样的:
print 'Hello %(name)s!' %{"name":"Tom"}
例如:
value = {"greet":"Hello world","Language":"Python"}
print "%(greet)s from %(language)s." %value
更Pythonic风格的代码如下:
print "{greet} from {language}.".format(greet="helloworld",language="python")
举例7:
Pythonic的库或框架
Flask
generators
1.避免只用大小写来区分不同的对象 如:a是一个数值型的变量,A是string类型.
2.避免使用容易引起混淆的名称. element,list,dict
3.不要害怕过长的变量名
4.深入认识Python有助于编写Pythonic代码
最好的学习方法是通读官方手册中的Language Reference 和 library Reference
深入学习业界中公认的比较Pythonic的代码,比如Flask,gevent和requests等
4.遵守pep8规范
pip install -U pep8
在自己的shell中执行这一命令就可以安装成功.
缩进和{}
c,c++,java等语言都是使用花括号{}来分隔代码段不同,Python中使用严格的代码缩进方式分隔代码块.
‘与”
c语言中’和”严格区分,单引号是代表严格字符,”代表一个字符串.
python中没有明显的区别,只在输入字符串内容不同的时候,使用上有微小的差异.
string1 = “He said, \”Hello\”” #字符串中本身的双引号需要转义
string2 = ‘He said,”hello”’ # 字符串中本身的单引号不需要转义
三元操作符 “?:”
c?X:y c中写法
x = 0
Y = -2
print x if xelse Y python中三目的写法
switch...case
switch(n){
case 0:
printf("You typed zero.\n");
break;
case 1:
printf("You are in top.\n"):
break;
default:
printf("Only single-digit numbers are allowed\n")
break
python 中没有switch case
写法如下:
if n== 0:
print "you type zero.\n"
elif n == 1:
print "you are in top.\n"
else:
print "Only single-digit numbers are allowed\n"
或者使用一下跳转表来实现:
def f(x):
return {
0: "you typed zero.\n",
1: "you are in top.\n",
}.get(n,"Only single-digit numbers are allowed\n")