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) Pythonic代码风格
交换两个变量
C语言代码如下:
1 int a = 1, b = 2;
2 int tmp = a;
3 a = b;
4 b = tmp;
5
6 //如果两个变量都为整数类型,当然也可使用:
7
8 int a = 1, b = 2;
9 a = a^b;
10 b = a^b;
11 a = a^b;
12
13 //这样的形式,可以不用引入第三个变量
Pythonic代码如下:
1 a, b = b, a
Python可以灵活的使用迭代器,安全的关闭文件描述符,如下:
1 for i in alist:
2 do_sth_with(i)
3
4 with open(path, 'r') as f:
5 do_sth_with(f)
Pythonic追求的是对Python语法的充分发挥,写出的代码带Python味儿,而不是看着向C或JAVA代码;
不应过分使用技巧
1 a = [1, 2, 3, 4]
2 b = 'abcdef'
3 print a[::-1]
4 print b[::-1]
使用Python比较多的人可以比较容易看出其作用,就是输出逆序的a和b,但还是比较晦涩,Pythonic追求的是充分利用Python语法,上面代码可写为:
1 a = [1, 2, 3, 4]
2 b = 'abcdef'
3 print list(reversed(a))
4 print list(reversed(b))
字符串格式化
我们很多人一般这样写,比较简洁:
1 name = 'Tom'
2 age = '20'
3 print 'Hello %s, your age is %s !' % (name, age)
其实,%s是比较影响可读性的,尤其是数量多了之后,很难清楚哪个占位符对应哪个实参,比较Pythonic的代码如下:
1 value = {'name': 'Tom', 'age': '20'}
2 print 'Hello %(name)s, your age is %(age)s !' % value
使用%占位符的形式,依旧不是Python最推荐的,最具Pythonic风格的代码如下:
1 print 'Hello {name}, your age is {age} !'.format(name = 'Tom', age = '20')
str.format()是Python最为推荐的字符串格式化方法;
1 class _const:
2
3 class ConstError(TypeError): pass
4 class ConstCaseError(ConstError): pass
5
6 def __setattr__(self, name, value):
7 if name in self.__dict__:
8 rasie self.ConstError, "Can't change const.%s" % name
9 if not name.isupper():
10 raise self.ConstCaseError, "const name '%s' is not all uppercase" % name
11
12 self.__dict__[name] = value
13
14 import sys
15 sys.modules[__name__] = _const()
无论是用哪种方式,都应该将常量集中到一个文件中,便于维护管理;