Download General The null object: None Tuple (): immutable and for

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
General The null object: None Tuple (): immutable and for heterogeneous data List []: mutable and for homogeneous data Dict {}: associative array, e.g., {'one':1, 'two':2} Non-­‐keyworded var-­‐length arg list: *args Keyworded var-­‐length arg list: **kwargs Swapping: a,b=b,a
zip([1,2,3],['a','b','c']) returns the list of tuples [(1,
'a'),(2,'b'),(3,'c')]
Different ways of looping through a list L: for index in range(len(L)): for item in L:
for index, item in enumerate(L):
it = iter(L)
it.next()
# raises exception if no more elements
Looping through multiple lists: for x,y in zip(lst1,lst2)
for x,y in map(None,lst1,lst2)
Retrieving values from a dict:
map(somedict.get, keys)
or [somedict[key] for key in keys] Creating a list of lists: [[0 for col in range(nCols)] \
for row in range(nRols)]
note that the following duplicates references to the first col:
[[0]*nCols]*nRows # DO NOT use
Cloning a list which may contain sub-­‐lists: copy.deepcopy Adding item to dictionary value that is a list: somedict.setdefault(key,[]).append(val)
Reduction is underused and powerful, e.g., the multiplication equivalent of sum: import operator
reduce(operator.mul, [1,2,3,4])
Exception handling try:
if len(args) == 0:
raise Exception('No args')
except Exception as exc:
print exc.message
else:
...
finally:
...
Data conversion Byte list → string: array('B', lst).tostring() String → byte list: array('B', s).tolist() Text processing Unicode string: u"Hello World" Multi-­‐line strings: "line 1\
line2"
"""line1
line2"""
Joining strings: '\n'.join(listoflines)
Process characters: map(func, s)
Check if string contains any character from some set: from functools import reduce
from operator import and_, or_
reduce(or_, map(s.__contains__, someset))
Alignment: ljust, rjust, center, e.g.
'Hello world'.ljust(width)
Outputting Unicode strings: sys.stdout=codecs.lookup('utf-8')[-1](sys.stdout)
print(s) Regular expression x* matches 0 or more repetitions of x x+ matches 1 or more repetitions of x x? matches 0 or 1 appearance of x *?, +?, ?? make the qualifiers non-­‐greedy ^ matches the start of a string x{m} matches m copies of x x{m,n} matches m to n copies of x x{m,n}? matches the least number of copies of x Lookahead assertion:
(?=x) matches if x matches next (?!x) matches if x does not match next Lookbehind assertion: (?<=x) matches if x matches previously (?<!x) matches if x does not match previously Searching and sorting Python used to use a hybrid of samplesort (a quicksort variant) for big lists and binary insertion sort for small lists; it now uses timsort Decorate-­‐sort-­‐undecorate: # sort by surname, then
orglst = ['Peter Pan', 'Peter Parker']
auxlst = map(lambda x: (x.split()[-1], x), orglst)
auxlst.sort()
# sort a list of tuples
orglst = map(lambda x: x[-1], auxlst)
To reverse-­‐sort strings, reverse the strings first (Python 2.x): import string
allchars = string.maketrans('','')
revlst = list(allchars)
revlst.reverse()
revchars = ''.join(revlst)
revs = 'abcdef'.translate(string.maketrans(\
allchars, revchars))
Priority queue: import bisect
q = []
# list of tuples of task ID and priority
tasks = [('Task 1',1), ('Task 2',3), ('Task 3',2)]
for t in tasks:
bisect.insort(q, (t[1], t[0]))
Itertools module Iterators: count, cycle, repeat Object-­‐oriented programming class SomeClass:
def __init__(self):
self.data = init_data
def SomeFunc(self, d):
self.data = d
Check/get for attribute: hasattr(o,attr), getattr(o,attr)
Files Writing to file: print >> file, sometext
file.write(sometext) Networking TCP server: from socket import *
sin = socket(AF_INET, SOCK_STREAM)
sin.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
sin.bind(('localhost',someport))
sin.listen(1)
try:
while 1:
sconn, addr = sin.accept()
while 1:
recvdata = sconn.recv(1024)
if not recvdata: break
sconn.close()
finally:
sin.close()
Threads, processes and synchronization Extending and embedding References David Ascher, Anna Martelli Ravenscroft, and Alex Martelli, “Python Cookbook,” 2nd ed., O'Reilly Media, 2005.