Python in a Nutshell (Useful Tips)

List

lambda Expressions

1
2
3
4
5
6
7
8
>>> aList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> low = 3
>>> high = 7
>>> filter(lambda x, l=low, h=high: h>x>l, aList)
[4, 5, 6]
# or
>>> def within_bounds(value, l=low, h=high):return h>value>l
>>> filter(within_bounds, aList)

Generators

通过迭代器触发,函数体并不执行; yield expression

1
2
3
4
def frange(start, stop, step=1.0):        
    while start < stop:        
        yield start        
        start += step

class

For any class object C, any object x, and any identifier S (except __name__, __bases__, and __dict__), C.S=x is equivalent to C._ _dict_ _['S']=x.

1
2
3
4
5
6
class C1(object):
    x = 23  
print C1.__name__, C1.__bases__
C1.y = 45
C1.__dict__['z'] = 67
print C1.x, C1.y, C1.z

There is no difference between class attributes created in the class body, outside the body by assigning an attribute, or outside the body by explicitly binding an entry in C.__dict__.

__name__
__bases__
__dict__
__init__
__setattr__
__set__
__get__
__new__

When you call C(*args,**kwds) to create a new instance of class C, Python first calls C.__new__(C,*args,**kwds). Python uses __new__’s return value x as the newly created instance. Then, Python calls C._ _init_ _(x,*args,**kwds), but only when x is indeed an instance of C or any of its subclasses (otherwise, x’s state remains as __new__ had left it).

1
2
x = C.__new__(C, 23)
if isinstance(x, C): type(x).__init__(x, 23)

Decorators

1
2
3
4
5
6
7
def f(cls, ...):
    ...definition of f snipped...
f = classmethod(f)
#等价于
@classmethod
def f(cls, ...):
...definition of f snipped...

modules

1
2
3
import optparse
import itertools
import re

Strings

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
s.capitalize( )
s.center(n, fillchar=' ')
>>> 'x'.center(9,'*')
'****x****'
s.count(sub,start=0,end=sys.maxint)
s.decode(codec=None,errors='strict')
s.encode(codec=None,errors='strict')
s.endswith(suffix,start=0,end=sys.maxint)
s.expandtabs(tabsize=8)
s.find(sub,start=0,end=sys.maxint)
s.index(sub,start=0,end=sys.maxint)
s.isalnum( )
s.isalpha( )
s.isdigit( )
s.islower( )
s.isspace( )
s.istitle( )
s.isupper( )
s.join(seq)
>>> "*".join(str(x) for x in range(7))
'0*1*2*3*4*5*6'
s.lstrip(x=string.whitespace)
s.rstrip(x=string.whitespace)
s.replace(old,new,maxsplit=sys.maxint)
s.ljust(n,fillchar=' ')
s.rjust(n,fillchar=' ')
s.split(sep=None,maxsplit=sys.maxint)
s.splitlines(keepends=False)
s.startswith(prefix,start=0,end=sys.maxint)
s.strip(x=string.whitespace)

Regular Expressions for String

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# r.findall(s)
import re
reword = re.compile(r'\w+') # reword = re.compile('(\w+)\s')
for aword in reword.findall(open('afile.txt').read()): print aword

# r.finditer(s)

# r.match(s,start=0,end=sys.maxint)
import re
digs = re.compile(r'\d+')
for line in open('afile.txt'):
    # to print all lines in a file that start with digits
    if digs.match(line): print line,

# r.search(s,start=0,end=sys.maxint)
import re
digs = re.compile(r'\d+')
for line in open('afile.txt'): 
    # to print all lines containing digits
    if digs.search(line): print line,
    
# r.split(s,maxsplit=0)
import re
rehello = re.compile(r'hello', re.IGNORECASE)
astring = ''.join(rehello.split(astring))

# r.sub(repl,s,count=0)
import re
rehello = re.compile(r'hello', re.IGNORECASE)
astring = rehello.sub('', astring, 1)

# r.subn(repl,s,count=0)
import re
rehello = re.compile(r'hello', re.IGNORECASE)
junk, count = rehello.subn('', astring)
print 'Found', count, 'occurrences of "hello"'