# looping dicts for k, v in knights.iteritems(): print k, v # looping sequences for i, v in enumerate(Seq): print i, v # dict from lists dict(zip(keyList, valList)) # dict from lists dict(zip(keyStr.split(' '), valString.split(' '))) # dict from obj attribs dict((name, getattr(ob, name)) for name in dir(ob) if not name.startswith('__')) # concat strings 1 ''.join([xStr, yStr]) # concat strings 2 xStr = ''.join([xStr, yStr]) # map 1 seq = range(10) def cube(x): return x*x*x map(cube, seq) # map 2 seq = range(10) def add(x, y): return x+y map(add, seq, seq) # reduce seq = range(10) def add(x, y): return x+y reduce(add, seq) # list comprehension 1 vec = [2, 4, 6] [3*x for x in vec] # list comprehension 2 if vec = [2, 4, 6] [3*x for x in vec if x > 3] # list comprehension 3 list vec = [2, 4, 6] [[x,x**2] for x in vec] # list comprehension 4 dict vec = [2, 4, 6] [{x:x**2} for x in vec] # list comprehension 5 v1, v2 vec1 = [2, 4, 6] vec2 = [4, 3, -9] [x*y for x in vec1 for y in vec2] # rightmost for varies first # [8, 6, -18, 16, 12, -36, 24, 18, -54] # list comprehension 6 v1, v2 dicts vec1 = [2, 4, 6] vec2 = [4, 3, -9] [{x:y} for x in vec1 for y in vec2] # rightmost for varies first # [{2: 4}, {2: 3}, {2: -9}, {4: 4}, {4: 3}, # {4: -9}, {6: 4}, {6: 3}, {6: -9}] # list comprehension 7 nested mat = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ] [[row[i] for row in mat] for i in range(len(mat[0]))] # Above list comprehension inverts the matrix # :)To avoid apprehension when nesting list comprehensions, # read them from right to left. :) # zip x = ['1', '2', '3'] y = ('4', '5', '6') z = "789" zip(x, y, z) # [('1', '4', '7'), ('2', '5', '8'), ('3', '6', '9')] # returns a list of tuples, where the i-th tuple contains the i-th # element from each of the argument sequences or iterables. # readFile2String f = open('c:/', 'r') #on windows add 'b'==binary s = f.read() f.close() # readFile2String 1 liner f = open('c:/test.txt', 'r'); s = f.read(); f.close() # readLines f = open('c:/', 'r') #on windows add 'b'==binary for line in f: # process(line) f.close() # writeString f = open('c:/', 'w') #on windows add 'b'==binary f.write('This is a test\n') #\n is NOT automatically added! f.close() # writeString 1 liner f = open('c:/', 'w'); f.write('This is a test\n'); f.close() # cd import os os.chdir(r"C:\1d\GoogleDev\appEnginePjs") # pwd import os os.path.abspath(os.curdir) # string replace s = 'spam bacon ham spam ham bacon spam' s.replace('spam', 'eggs',1) #one s.replace('spam', 'eggs') #all