Python日积月累

来源:互联网 发布:vue.js 遮罩层 编辑:程序博客网 时间:2024/05/19 17:51

Python使用技能:

1.  列出目录下所有文件

import osset = os.listdirs(*)
这条命令会列出目录下所有的文件和文件夹,但所有列出条目的排序是原始文件系统中的排序,使用前一般需要排序。

使用下面这条命令就可以得到和文件夹中直观看到的顺序相同的排序:

set = os.sort()

更多排序可以参考cdw_FstLst的博客,如按字母排序、使用lambda表达式等。

2.  numpy.where()

(1)numpy.where()可以根据条件从n维数组中筛选元素,返回位置索引。如

x = np.arange(9.).reshape(3, 3)np.where( x > 5 )(array([2, 2, 2]), array([0, 1, 2]))

(2)numpy.where()可以看做三目运算符,且支持嵌套调用

numpy.where(condition[, x, y])
等价于

if condition(arr[i]):    arr[i] = xelse:    arr[i] = y

嵌套调用参阅豆瓣博文。
(3)当使用numpy筛选,包含多个condition时,需要使用numpy的逻辑运算:numpy.logical_and(c1, c2),  numpy.logical_or(c1, c2), numpy.logical_not(c1, c2)。例如,需要从一个array中选择出:x > a1且x < a2的所有元素,需要使用

numpy.logical_and(x > a1, x < a2)

文本

文本

(4)Dictionary

D = {'a': 1, 'b': 2, 'c': 3}for key in D:    print(key, '=>', D[key])for (key, value) in D.items():    print(key, '=>', value)


5. 并行编程

    在处理图像等数据时,数据量巨大,每个数据的操作相同,这种情况下使用并行编程可以充分发挥机器性能,缩短计算时间。Python支持多进程(process)和多线程(thread),一般使用多进程实现并行加速。

(1)用map实现(参考世界看我我看世界的博客)

    借助multiprocessing模块中Pool()下的map方法,实现并行,形式为

map(func, iterable[, chunksize=None])
举例:

import timefrom multiprocessing import Pooldef run(fn):    time.sleep(1)    return fn*fnif __name__ == "__main__":    testFL = [1,2,3,4,5,6]    print 'in order:'    s = time.time()    for fn in testFL:        run(fn)    e1 = time.time()    print('order time: %d' % int(e1 - s))    print 'parallel:'    pool = Pool(20)    rl = pool.map(run, testFL)    pool.close()    pool.join()    e2 = time.time()    print('parallel time %d' % int(e2-e1))    print rl

(2)传入多个参数(参考Arkenstone的博客)

    上述map的方法只能接受一个输入参数,当需要输入多个参数时,可以使用zip对参数进行打包,并在对应的函数中用列表解析获取相应的变量值。

举例

import timefrom multiprocessing import Pooldef run((p1, p2)):    print(p1, p2)if __name__ == "__main__" :    startTime = time.time()    testFL = [1, 2, 3, 4, 5]    testLF = [6, 7, 8, 9, 10]    pool = Pool(2)    pool.map(run, zip(testFL, testLF))    pool.close()    pool.join()    endTime = time.time()    print "time :", endTime - startTime


注意,使用map做并行编程时,传入的参数必须是iterable的,如list,string,generator等。为了简洁,可以考虑使用全局变量,在map之前设定global variable的值,再直接并行运行程序。