Python note

· Read in about 3 min · (454 Words)

I plan to use Python as one of my main programming language for its huge numbers of libraries.

last update 2015-8-14

IDE

Data structure

  • complex structure data.setdefault('names', []).append('Ruby')
  • get element data.get('foo', 0) # not data['foo']
  • [3*x for x in vec if x > 3] # [(x, x**2) for x in vec]
  • iterate for x, y in data.iteritems():
  • iterate through two sequences same time for x, y in zip(a, b):

Strings

  • z.lower() # upper()
  • s.isalpha() # s.isdigit()
  • s.split(" ") "-".join("GNU/Linux is great".split(" "))
  • s.strip() # s.lstrip("cwsd.") s.rstrip("cwsd.")
  • s.find("for") # s.startswith("fa") # s.endwith("fa")
  • s[::-1] # s.reverse()
  • 'tea␣for␣too '. replace ('too ', 'two ')
  • s.join(s2) is faster than s + s2
  • "%s\n" % s is faster than s + "\n" . and "{0}\n".format(s) is recommended.
  • str.isspace()
  • str.ljust(width[, fillchar]) str.center(width[, fillchar]) str.rjust(width[, fillchar])
  • Format examples
  • Template strings

Set

  • isdisjoint(other), issubset(other), issuperset(other)``
  • union(other, …), intersection(other, …), difference(other, …)`
  • update(other, …), add(elem), discard(elem)

Dict

  • get(key[, default]) Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises aKeyError

sort

dic = {'a':31, 'bc':5, 'c':3, 'asd':4, 'aa':74, 'd':0}
dict= sorted(dic.iteritems(), key=lambda d:d[1], reverse = True) # by value
# [('aa', 74), ('a', 31), ('bc', 5), ('asd', 4), ('c', 3), ('d', 0)]
dict= sorted(dic.iteritems(), key=lambda d:d[0]) # by key

Collections

Performance

  • if is True is faster than if == True
  • x < y < z faster than x < y and y < z
  • while 1 faster than while True
  • 2**20 faster than pow(2,20)
import cPickle
import pickle
a = range(10000)
%timeit -n 100 x = cPickle.dumps(a)

%timeit -n 100 x = pickle.dumps(a)

100 loops, best of 3: 1.58 ms per loop
100 loops, best of 3: 17 ms per loop

Function

def change(b):
    global a
  • Default argument value def test(a , b=-99):
  • Keyword-only Args def cleanup(folder, *, extreme=False):
  • map print(map(square, lst))

File handling

>>> with open('setup.py') as fobj:
...     for line in fobj:
...         print line,
sys.stderr.write

gzip — Support for gzip files

Path

  • use import os , instead of from os import * .
  • os.path.exists(path):
  • os.getcwd() # os.chdir(‘/tmp’)
  • os.system(“ls”)
  • pathlib
  • shutil
shutil.copyfile(src, dst, *, follow_symlinks=True)
shutil.copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False)
shutil.move(src, dst)

shutil.rmtree(path, ignore_errors=False, onerror=None)
  • glob.glob(’*.py’)

Re

Re

Exceptions

Exceptions

try:
    do_some_func()
except KeyboardInterrupt:
    print "User Press Ctrl+C,Exit"
except EOFError:
    print "User Press Ctrl+D,Exit"

Others

Misc

  • Advanced Unpacking
>>> a, b, *rest = range(10)
>>> a
0
>>> b
1
>>> rest
[2, 3, 4, 5, 6, 7, 8, 9]
Get the first and last lines of a file:
>>> with open('using_python_to_profit.txt') as f:
        first, *_, last = f.readlines()
>>> first
'Step 1: Use Python 3\n'
>>> last
'Step 10: Profit!\n'