sam分类算法python代码_Python性能鸡汤_实践Sam

Python性能鸡汤   一文见:http://www.oschina.net/question/1579_45822

下面是关于其中一些点,我的实践:

1. 内建函数:

2. join()连接字符串:

l=['aa','bb']

mystring = ",".join(l)

print mystring

import string

ss=['hehe','haha',"xixi"]

print string.join(ss,'')

[[email protected] script]$ python test.py

aa,bb

hehehahaxixi

8. list comprehension

漂亮地实现 python 数组遍历

>>> arrayA = [1,2,3,4,5,6,7]

>>> arrayB = [ number for number in arrayA if number % 2 ]

>>> print arrayB

[1, 3, 5, 7]

我们把这段代码用括号分成三个部分:(number) (for number in arrayA) (if number % 2)

第一部分,表明我们的新数组的元素表示为number;

第二部分,是说number是取之于数组arrayA的遍历;

第三部分,是说是否产生该元素的条件,即当number取2的模为非0数的时候(奇数)就选取该number。

下面的例子使用了2個 for

nums = [1,2,3]

fruit = ["Apples", "Peaches", "Bananas"]

print [(i,f) for i in nums for f in fruit]

上面的程式會印出

[(1, 'Apples'), (1, 'Peaches'), (1, 'Bananas'),

(2, 'Apples'), (2, 'Peaches'), (2, 'Bananas'),

(3, 'Apples'), (3, 'Peaches'), (3, 'Bananas')]

下面的例子使用了2個 for 跟2個 if

nums = [1,2,3]

fruit = ["Apples", "Peaches", "Bananas"]

print [(i,f)for i in nums for f in fruitif i % 2 == 1 if f[0] == 'P']

上面的程式會印出

[(1, 'Peaches'), (3, 'Peaches')]

摘自:

http://blog.ipattern.org/archives/600

http://descriptor.blogspot.com/2008/11/python-idiom-list-comprehensions.html

9. xrange()替代range()

据说range比xrange开销要大,原因是range会直接生成一个list对象,而xrange每次调用返回其中的一个值;参考:http://yushunzhi.iteye.com/blog/207850。于是好奇做了个小小的测试,比较两个函数性能到底有多大差别。

#!/usr/bin/env python

from datetime import *

def test_range():

c1=0

t1 = datetime.now()

for i in range(0,100000):

c1 += 1

print datetime.now()-t1

def test_xrange():

c1=0

t1 = datetime.now()

for i in xrange(0,100000):

c1 += 1

print datetime.now()-t1

if __name__ == '__main__':

test_range()

test_xrange()

结果

从上图的三次运行结果可以看出,range在相同计算量下用时比xrange多了70%左右。另外,在不同的计算量情况下,用时基本也维持在这个比例。因此,如果并不需要返回list对象的话,xrange会是个好选择。

11. itertools模块: 排列组合

>>> import itertools

>>> iter=itertools.permutations([1,2,3])

>>> print iter

>>> tuple(iter)

((1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1))

>>> tuple(iter) #用完一次就没了

()

>>>

>>> import itertools

>>> iter=itertools.permutations([1,2,3])

>>> list(iter)

[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

>>> list(iter)

[]

>>> test = combinations([1,2,3,4], 2)

>>> for el in test:

... print el

...

(1, 2)

(1, 3)

(1, 4)

(2, 3)

(2, 4)

(3, 4)

你可能感兴趣的:(sam分类算法python代码)