Here are some Python links and idioms.
Python Links
recipes , pyDocs , DiveIn, FredrikLundh , FredrikLundhPython
wiki, examples, community, questions
idioms.colorado.edu, idioms.c2.com, idioms.python.org, idioms.caltech
samples.python.org.moin, samples.wikibooks.org, samples.python.org.doc
bruce.eckel.artima, bruce.eckel.lovePython, bruce.eckel.TIPython
Python Idoms
class
class BankAccount(object):
def __init__(self, initial_balance=0):
self.balance = initial_balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
self.balance -= amount
def overdrawn(self):
return self.balance < 0
my_account = BankAccount(15)
my_account.withdraw(5)
print my_account.balance
looping dicts
for k, v in knights.iteritems():
print k, v
looping enumerated sequences
for i, v in enumerate(Seq):
print i, v
dict from k v lists
dict(zip(keyList, valList))
dict from k v strings
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 2 string
|
s = ''.join(L)
|
list creations
|
iota=range(5)
zeros=[0]*5
foos=['foo']*8
L=[0,1,2] + [3,4]
four=L[-1]
three=L[-2]
zero_1=L[:2]
two_3_4=L[2:]
one_2_3=L[1:4]
del(L[1])
listoflists=[ [0]*4 ] *5
listoflists=[[0]*4 for i in range(5)]
|
list comprehension [simple]
|
vec = [2, 4, 6]
[3*x for x in vec]
|
list comprehension [if]
|
vec = [2, 4, 6]
[3*x for x in vec if x > 3]
|
list comprehension [list]
|
vec = [2, 4, 6]
[[x,x**2] for x in vec]
|
list comprehension [dict]
|
l1=1,2,3,4,5; l2=6,7,8,9,0
dict([(k, v) for k,v in zip(l1,l2)])
# {1: 6, 2: 7, 3: 8, 4: 9, 5: 0}
|
list comprehension [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 [tuples l1, l2]
|
l1=1,2,3; l2=6,7,8
[{x:y} for x in l1 for y in l2]
# rightmost for varies first
# [{1: 6}, {1: 7}, {1: 8}, {2: 6}, {2: 7}, {2: 8}, {3: 6}, {3: 7}, {3: 8}]
|
list comprehension [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 1 liner
|
for line in file('fileName.txt').readlines():
|
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') # newline 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: d\GoogleDev ppEnginePjs")
|
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
|
string2list
|
L = list(s)
|
string2list [split]
|
L = s.split('#')
|
sorted dict print formatted
|
cnid = chordNameIntervalDict= {
'maj': (0, 4, 7),
'min': (0, 3, 7),
'aug': (0, 4, 8),
'dim': (0, 3, 6),
'sus2': (0, 2, 7),
'sus4': (0, 5, 7),
'6': (0, 4, 7, 9),
'm6': (0, 3, 7, 9),
'7': (0, 4, 7, 10),
'maj7': (0, 4, 7, 11),
'm7': (0, 3, 7, 10),
'dim7': (0, 3, 6, 10),
}
#make the keys be the vals and the vals the keys
icnd = intervalChordNameDict = dict([(cnid[k],k) for k in cnid.keys()])
chordNameL = 'maj,min,aug,dim,sus2,sus4,6,m6,7,maj7,m7,dim7'.split(',')
print 'cnid'
for k in chordNameL:
print ('%7s %s')%(str(k),str(cnid[k]))
print 'icnd'
for k in sorted(icnd):
print ('%-16s %s ')%(k, icnd[k])
|
enum_string 2 dict
|
enum_string = es = "state, county, city_state, city_name, city_url"
ed = dict(zip(es.split(", "), range(len(es))))
print ed
{'county': 1, 'city_name': 3, 'state': 0, 'city_url': 4, 'city_state': 2}
|
try except
|
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except IOError as (errno, strerror):
print "I/O error({0}): {1}".format(errno, strerror)
except ValueError:
print "Could not convert data to an integer."
except:
print "Unexpected error:", sys.exc_info()[0]
raise
|
cgi
|
#!/usr/bin/env python
# from: http://webpython.codepoint.net/cgi_file_upload
import cgi, os
import cgitb; cgitb.enable()
try: # Windows needs stdio set for binary mode.
import msvcrt
msvcrt.setmode (0, os.O_BINARY) # stdin = 0
msvcrt.setmode (1, os.O_BINARY) # stdout = 1
except ImportError:
pass
form = cgi.FieldStorage()
def upload():
""" upload the file into files/ """
fileitem = form['file']
# Test if the file was uploaded
if fileitem.filename:
# strip leading path from file name to avoid
# directory traversal attacks
fn = os.path.basename(fileitem.filename)
open('files/' + fn, 'wb').write(fileitem.file.read())
message = 'The file "' + fn +
'" was uploaded successfully'
else:
message = 'No file was uploaded'
print """\
Content-Type: text/html\n
%s
""" % (message,)
def main():
#cgi.test()
message = 'from main '
for k in form.keys():
if k != 'file':
message = ''.join([message,
k+': '+form.getvalue(k)+' '])
print """\
Content-Type: text/html\n
%s
""" % (message,)
main()
|
var lastId = 36;
function dr(id){
// http://www.javascriptf1.com/tutorial/javascript-hide-table-row.html
var row = document.getElementById(id);
if (row.style.display == ”)
row.style.display = ‘none’;
else
row.style.display = ”;
}
function collapseAll(){
//alert(lastId)
for(id=0;id<=lastId;id++){
var row = document.getElementById(id);
row.style.display = 'none';
}
}
function expandAll(){
//alert(lastId)
for(id=0;id<=lastId;id++){
var row = document.getElementById(id);
row.style.display = '';
}
}
collapseAll()
#idioms, #programming, #python |