Monday, October 29, 2012

Introduction to Python

 2012-10-15      

=====================


Tom 2012-10-15 09:57
1. zip((1,2,3),(7,8) ==> [(1,7),(2,8)]; zip(list/tuple, list/tuple, ...); no (3,-)

2. enumerate([7,8,9]) ==> {(0,7),(1,8),(2,9)}; enumerate(list | tuple | set | range)


3. @myDecorator : to change the following decorated function for probing
3a. myDecorator can be a class or function
3b. if class, class myDecorator(object):
    def __init__(self,f): self.f = f;
    def __call__(self): ...self.f()...;
3c. if function, def myDecorator(f): def new_f():...f()...; return new_f;

3d. @A; def f():pass; ==> f=A(f);
3d2. def myDecorator(f):
        # def new_f(*args, **kwargs): return f(*args, **kwargs); 
        def new_f(*args): return f(*args); 
        return new_f;

3e. @A(args); def f():pass; ==> _deco=A(args); f=_deco(f);
3e1. @A(args); def f():pass; ==> f=A(args)(f)
3e2. def myDecorator(arg1, arg2):
    def _deco(f): def new_f(*args): return f(*args); return _deco;

3g. ATTENTION, decoration will execute function myDecorator(), or method myDecorator.__init__()

4. yield vs return : 
    yield : pause the function, and return a value; next() to resume
    return : stop the function, and return a value
flicker 彩虹炫 | flicker 匿名卡 | 编辑 删除 IP: 98.118.242.96Tom 2012-10-15 09:58
1. the function needs to be defined before invocation; unless invoked by another function. 

2. __doc__ can be set for a module/file, class, function; it locates at the first line, not counting the comments. 

3. "\" for unfinished line
flicker 彩虹炫 | flicker 匿名卡 | 编辑 删除 IP: 98.118.242.96Tom 2012-10-15 10:01
To get all numbers into one-level list
    x=[]; temp2=[x.extend(list(data2[y][3:9])) for y in range(len(data2))]

To get all 3rd numbers in one-level list    
    x=[data2[y][3] for y into range(len(data2))]

for x,y,z in ((1,2,3),(4,5,6)): print x,y,z
for x,(y,z) in [(1,2,3),(4,5,6)]: print x,y,z;
flicker 彩虹炫 | flicker 匿名卡 | 编辑 删除 IP: 98.118.242.96Tom 2012-10-15 10:19
UNKNOWN.....

try: func();
except errorMessage:
except:
else: 
...
def func(): ...raise errorFunc(string);...;
flicker 彩虹炫 | flicker 匿名卡 | 编辑 删除 IP: 98.118.242.96Tom 2012-10-16 14:52
- power of "for" in making a list

[''.join(perm) for i in range(1, len(s)) for perm in it.permutations(s, i)]
flicker 彩虹炫 | flicker 匿名卡 | 编辑 删除 IP: 98.118.242.96Tom 2012-10-16 15:00
print "[%i, %i, %i]" % tuple(numberList)
print "[%s, %s, %s]" % (1, 2, 3)
print "[{0}, {1}, {2}]".format(1, 2, 3)
print "[{one}, {two}, {three}]".format(three=3, two=2, one=1)
print "[%(one)i, %(two)i, %(three)i]" % {'three':3,'two':2,'one':1}
print('[{},{},{}]'.format(1,2,3))
print "%s, %s number %d" % (vfoo, vbar, vbaz)
flicker 彩虹炫 | flicker 匿名卡 | 编辑 删除 IP: 98.118.242.96Tom 2012-10-16 15:09
"First, thou shalt count to {0}" # References first positional argument
"Bring me a {}"                  # Implicitly references the first positional argument
"From {} to {}"                  # Same as "From {0} to {1}"
"My quest is {name}"             # References keyword argument 'name'
"Weight in tons {0.weight}"      # 'weight' attribute of first positional arg
"Units destroyed: {players[0]}"  # First element of keyword argument 'players'.

"Harold's a clever {0!s}"        # Calls str() on the argument first
"Bring out the holy {name!r}"    # Calls repr() on the argument first

>>> '{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'
>>> '{2}, {1}, {0}'.format(*'abc')      # unpacking argument sequence
'c, b, a'
>>> coord = (3, 5)
>>> 'X: {0[0]};  Y: {0[1]}'.format(coord)
'X: 3;  Y: 5'

>>> '{:<30 aligned="aligned" br="br" format="format" left="left" style="word-wrap: break-word;">'left aligned                  '
>>> '{:>30}'.format('right aligned')
'                 right aligned'
>>> '{:^30}'.format('centered')
'           centered           '
>>> '{:*^30}'.format('centered')  # use '*' as a fill char
'***********centered***********'

>>> '{:+f}; {:+f}'.format(3.14, -3.14)  # show it always
'+3.140000; -3.140000'
>>> '{: f}; {: f}'.format(3.14, -3.14)  # show a space for positive numbers
' 3.140000; -3.140000'
>>> '{:-f}; {:-f}'.format(3.14, -3.14)  # show only the minus -- same as '{:f}; {:f}'
'3.140000; -3.140000'

>>> # format also supports binary numbers
>>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)
'int: 42;  hex: 2a;  oct: 52;  bin: 101010'
>>> # with 0x, 0o, or 0b as prefix:
>>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)
'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'
>>> '{:,}'.format(1234567890)
'1,234,567,890'
>>> 'Correct answers: {:.2%}'.format(0.8864)
'Correct answers: 88.64%'
flicker 彩虹炫 | flicker 匿名卡 | 编辑 删除 IP: 98.118.242.96Tom 2012-10-16 15:15
>>> import datetime
>>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
>>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
'2010-07-04 12:15:58'

'{0:{fill}{align}16}'.format(text, fill=valign, align=valign)
'{:02X}{:02X}{:02X}{:02X}'.format(*octets)
print '{0:{width}{base}}'.format(num, base=vbase, width=vwidth)
flicker 彩虹炫 | flicker 匿名卡 | 编辑 删除 IP: 98.118.242.96Tom 2012-10-16 15:22
>>> a = lambda: "{} World".format("Hello")
>>> b = lambda: "Hello" + " World"
>>> c = lambda: "%s World" % "Hello"
>>> d = lambda: "".join(("Hello", " World"))
>>> a(), b(), c(), d()
('Hello World', 'Hello World', 'Hello World', 'Hello World')
>>> timeit.timeit(a)
0.7830071449279785

"hi there %s" % name
"hi there %s" % (name,) 
tu = (12,45,22222,103,6)
print '{0} {2} {1} {2} {3} {2} {4} {2}'.format(*tu)
li = [12,45,78,784,2,69,1254,4785,984]
print map('the number is {}'.format,li)
flicker 彩虹炫 | flicker 匿名卡 | 编辑 删除 IP: 98.118.242.96Tom 2012-10-16 21:26
sublist = filter( lambda s, substring=S:
                     string.find(s, substring) != -1,
                  L)
sublist = [ s for s in L if string.find(s, S) != -1 ]
[ expression for expr in sequence1
             for expr2 in sequence2 ...
             for exprN in sequenceN
             if condition ]

filter(function, iterable)
Construct a list from those elements of iterable for which function returns true. 
map(function, iterable, ...)¶
Apply function to every item of iterable and return a list of the results.
zip([iterable, ...])¶
This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. 

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zipped)
>>> x == list(x2) and y == list(y2)
True
flicker 彩虹炫 | flicker 匿名卡 | 编辑 删除 IP: 98.118.242.96Tom 2012-10-16 21:31
>>> range(3, 6)             # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args)            # call with arguments unpacked from a list
[3, 4, 5]

>>> def parrot(voltage, state='a stiff', action='voom'):
...     print "-- This parrot wouldn't", action,
...     print "if you put", voltage, "volts through it.",
...     print "E's", state, "!"
...
>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
>>> parrot(**d)
-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
flicker 彩虹炫 | flicker 匿名卡 | 编辑 删除 IP: 98.118.242.96Tom 2012-10-16 21:55
jpython, jython
HTMLgen
PyQT

django
groke

web.py
pylon
tornado
wxpython
flicker 彩虹炫 | flicker 匿名卡 | 编辑 删除 IP: 98.118.242.96Tom 2012-10-17 21:30
print "%s %s" % ("a", "b")
print "%5.3s" % "abcde"  # ..abc where "." shows the space
print "%-5.3s" % "abcde"  # abc.. where "." shows the space 

print "%i" % 3.12345    # 3
print "%f" % 3.12345678    # 3.123457
print "%.8f" % 3.12345678    # 3.12345678
print "% i" % 3    # .3  where "." shows the space 
print "% i" % -3    # -3
print "%+i" % 3    # +3
print "%+i" %-3    # -3




No comments:

Post a Comment