Python notes(2)
assignments
a,b,c=x
Here the x , the RHS(Righthand side) should be
iterable with exactly 3 items!
augmented assignment the only differencs is that
the LHS object may be modified if it has
coresponding in-place method as __iadd__
for (+).
numeric conversion
implicit : from int, long, float, to complex.
explicit : give (int(), long(), float(), complex() )
a non-complex argument. Also can from a string.
int('435',25) #=> 2580
Arithmetic
-Qold command line switch make (/ and // ) equal.
-Qnew make / a true division or specify
from _ _future_ _ import division
in module file head.
1.*a/b to avoid making any assumption on the types of a and b
divmod(x,y) #=> return (quotient, remainder) pair
Sequence < Container < Iterable
Sequence has built-in function: len(cntnr) ,
min(itrbl), max(itrbl) , and sum(itrbl)
# repetition , concatenation
(3,)*3 #=> (3,3,3)
[24,23,]*-3 #=> []
(42,) + () + (0,) #=> (42, 0)
# membership test
3 in [3,4,5] and '22' in "get22in" #=> True
# indexing
S[-L,-L+1,...-1] = S[0,1,...L-1] #Using an index >=L or <-L raises an exception
# slicing
S[i:j(:l)] #=> all S[n] where i<=n<j
#=> i(=0, omit or <=-L)
#=> j(=L, omit or >=L)
#=> S[n] = S[L+n] if n<0
#=> l, the step, this is called extended mode
# list slicing modifying
S[i:i]=[1,2,3] #=> insert 1,2,3 before 'ith'
S[::2]=[1,2,..n] #=> should have same numbers as in this extended mode
List Methods:
Method | Description |
---|---|
L.count(x) | num of occurence of object 'x' |
L.index(x) | first index of 'x', or Exception |
L.append(x) L.extend(iterable) L.insert(i,x) L.remove(x) L.pop([i]) L.reverse() | as is |
Sorting!
L.sort([f]) #=> sort L ascending, as
#=> def cmp2ndword(a, b): return cmp(a.split( )[1], b.split( )[1])
#=> L.sort(cmp2ndword)
L.sort(cmp=cmp, key=None, reverse=False) #=> function: cmp(a,b) , key(x), reverse=True/False
#=> sorting works as cmp(key(x),key(y))
Note : Passing compare function is much slower than the following two methods
as (called decorate-sort-undecorate DSU)
A = [ (s.split( )[1], s) for s in L ]
A.sort( )
L[:] = [ t[1] for t in A ]
# or Use operator pass key= to sort (use cmp as few as possible)
import operator L.sort(key=operator.itemgetter(1))
Sets
Basic set operation :
Nonmutating | Mutating |
---|---|
copy() difference(S2) ('-' ) intersection(S2)('&' ) issubset(S2) issuperset(S2) symmetric_difference(S2)('^' ) union(S2)('|' ) | add(x) clear() discard(x) (no warning) pop()( kick one out) remove(x) (error not found) |
pop() is useful when want to save memory during a 'consuming' process
Dictionaries
Basic set operation :
Nonmutating | Mutating |
---|---|
copy() has_key(k) (as 'k in D') items() (list item a pair) keys() values() iteritems(),iterkeys(),itervalues() get(k[,x]) (D[k] or x if not k found) | clear() update(D1) (D1 update to D) popitem() setdefault(k[,x]), pop(k[,x]) |
popitem() is same useful as pop() in a set.
setdefault(k[,x]) same as get(k) but if not found auto-set it. pop(k[,x]) works oppositely which also does unbinding.
D[k] and pop(k) may raise exception, D.get(k[,x]) and pop(k,x) return x or None if not found.
update() semantics same as dict() :
dict([(1,2)])
dict(x=1)
dict({'z':1} ,x=42, y=2, z=7)
String formating
as C's printf, Python string offers output format as below:
Character | Outputformat |
---|---|
d,i | decimal integer |
u | unsigned integer |
o,x,X | unsigned octal, hexadecimal, Hexadecimal |
e,E | exponential form |
f,F | decimal form |
g,G | auto exponential/fixed point |
c | single character |
r | repr |
s | str |
% | % |
Modifier Character | Effects |
%(name) | use values from a dict |
%# | use alternate form to convert |
%0 | zero-padded |
%- | left-justified |
%space | one space padded to a positive number |
%+ | with (+/-) signs |
%*.* | take width.precision from values like "%. f" % (5,3,2.1) which is as same as "%5.3f" % 2.1 => "2.100" |
%s
will be auto-replaced with str(value) which is very useful as below:
one = "x:"+str(x)+" y:"+str(y) # same as below
another = "x:%s y:%s" %(x,y)
Another formatter is string.Template which could be subclassed to provide
customization(See Template strings).
Examples:
>>> from string import Template
>>> s = Template('$who likes $what') # construction
>>> s.substitute(who='tim', what='kung pao')
'tim likes kung pao'
>>> d = dict(who='tim')
>>> Template('Give $who $100').substitute(d) # $100 is not valid placeholder
Traceback (most recent call last):
[...]
ValueError: Invalid placeholder in string: line 1, col 10
>>> Template('$who likes $what').substitute(d)
Traceback (most recent call last):
[...]
KeyError: 'what'
>>> Template('$who likes $what').safe_substitute(d)
'tim likes $what'
looping
It's possible to extract multi values from an item during only one looping.
The item should be iterable and has exactly as many items as there are in the
target list.
for key, value in d.items( ):
if not key or not value: # keep only true keys and values
del d[key]
Note: Must not use d.iteritems() which del d[key] will raise a
runtime error : "dictionary changed size during iteration".
The iterable should not be modified (items in it could be).
xrange(n) and range(n) : xrange() will consume less memory but a little slower during
iterating. range() could be used wherever xrange() could but not vice versa.
else in Loop : If loop terminates via break, return or exception,
the else excutes.
pass : do nothing in a looping body which should never be empty.
0 Comments:
Post a Comment
<< Home