User Tools

Site Tools


python:cookbook

System level

  • Pass parameters in command line
# test.py name_1 name_2 ... name_n
# or python -i test.py name_1 name_2 ... name_n
import sys
parms = sys.argv  # return ['test.py", name_1, ... name_n]
  • Execute an external command
import os
os.system('ls')
  • time counter (tic/toc)
import time
tic = time.time()
... ...
toc = time.time()
elaps = toc-tic

File I/O

List/Tuple

How to reverse zip

  • Answer: use zip() in combination with a special unitary operator “*” which release elements from a list/tuple (i.e., effectively it removes “()” or “[]”). ( Ref1, Ref2) For example:
a = [1, 2, 3]
b = ['A', 'B', 'C']
z = zip(a, b)
# to reverse it
a, b = zip(*z)

Dictionary

Build dictionary

  • In Python 2.6 (or earlier), use the dict constructor:
d = dict((key, value) for (key, value) in sequence)
  • In Python 2.7+ or 3, you can just use the dict comprehension syntax directly:
d = {key: value for (key, value) in sequence}

Plot

  • Output plots into a multi-page pdf file
from matplotlib.backends.backend_pdf import PdfPages
 
fnpdf = 'out.pdf'
pdf = PdfPages(fnpdf)
 
...
 
for i in range(npage):
    ...
    pdf.savefig()
    show()  # you can remove this line if needed
 
pdf.close()
python/cookbook.txt · Last modified: 2016/11/26 13:54 by 127.0.0.1