Python日积月累

Python使用技能:

1.  列出目录下所有文件

import os
set = 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] = x
else:
    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 time
from multiprocessing import Pool


def run(fn):
    time.sleep(1)
    return fn*fn


if __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 time
from multiprocessing import Pool


def 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的值,再直接并行运行程序。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值