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
阅读全文
0 0
- python日积月累
- Python日积月累
- Python日积月累之isdigit()
- Python日积月累之 islower()
- python日积月累之isnumeric()
- python日积月累之isspace()
- python日积月累之join()
- python日积月累之ljust()
- python日积月累之lower()
- python日积月累之maketrans
- Python 知识点 记录 日积月累
- Python 知识点 记录 日积月累
- 日积月累
- 日积月累。
- 日积月累
- 日积月累
- 日积月累
- 日积月累
- 数组的复制和排序
- 决策树算法
- 《设计模式》学习笔记2——简单工厂模式
- Linux系统文件编程
- 数据结构实验之图论八:欧拉回路
- Python日积月累
- java中存在i+1<i这种情况。
- SPP-Net可以解决不同的数据集之间Scale不一致的问题
- LBPH+Adaboost人脸检测、识别
- beflameNext初学备注
- 在eclipse的maven插件中搜寻本地仓库中的jar搜索不到的解决方案
- Executors类
- 【嵌入式学习历程13】Linux进程控制编程
- CodeForces