python一行式编程技巧

88 阅读1分钟

1、快速访问linux服务器上的文件

 python -m http.server port

 此时访问浏览器

2、交换a,b的值

Type "help", "copyright", "credits" or "license" for more information.
>>> a,b=3,4
>>> a,b
(3, 4)
>>> b,a=a,b
>>> a,b
(4, 3)
>>> 

3、读取文件并按行生成列表

>>> [line.strip() for line in open('nlp.py')]
['import time', 'import os', 'os.environ["CUDA_VISIBLE_DEVICES"]="0,1"', 'st=time.time()', 'for i in range(1000000000):', 'pass', 'end=time.time()', 'print(end-st)']
>>> 

4、评估算法效率

[ldd@localhost ~]$ python -m cProfile nlp.py 
0.321498155594
         7 function calls in 0.322 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.216    0.216    0.322    0.322 nlp.py:1(<module>)
        1    0.000    0.000    0.000    0.000 os.py:470(__setitem__)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
        1    0.000    0.000    0.000    0.000 {posix.putenv}
        1    0.106    0.106    0.106    0.106 {range}
        2    0.000    0.000    0.000    0.000 {time.time}

5、根据编码找到字符

python -c "print unichr(65)"
[l@localhost ~]$ python -c "print unichr(65)"
A

6、其他

请参考python一行编程:wiki.python.org/moin/Powerf…