=================================================================
字典中的 get 函数
我们经常需要在字典中初始化数据:
以下是不好的实现方法:
navs = {}
for (portfolio, equity, position) in data:
if portfolio not in navs:
navs[portfolio] = 0
navs[portfolio] += position prices[equity]
使用dict.get(key, default) 删除 if 判断代码:
navs = {}
for (portfolio, equity, position) in data:
navs[portfolio] = (navs.get(portfolio, 0)
+ position prices[equity])
=================================================================
字典中的 setdefault 函数 (1)
当我们要初始化一个可变字典的值。每个字典的值将是一个列表。下面是不好的做法:
初始化可变字典的值:
for (portfolio, equity) in data:
if portfolio in equities:
equities[portfolio].append(equity)
else:
equities[portfolio] = [equity]
通过 dict.setdefault(key, default) 使这段代码工作的更好:equities = {}
for (portfolio, equity) in data:
equities.setdefault(portfolio, []).append(equity)
dict.setdefault()等同于“ get, or set & get“ 或"如果没有,就设置"; 如果你的字典Key是复杂的计算或long类型,使用 setdefault 是特别有效的。=================================================================
debug>>> import pdb
>>> import mymodule
>>> pdb.run(‘mymodule.test()’)
Cmdline:
python -m pdb myscript.py
In *.py src file:
import pdb
pdb.set_trace()
=================================================================
>>> import dis
>>> f = open(‘test.py’).read()
>>> co = compile(f, "test.py", "exec")
>>> dis.dis(co) #反汇编
4 0 LOAD_CONST 0 (None)
3 IMPORT_NAME 0 (gtk)
6 STORE_NAME 0 (gtk)
9 LOAD_CONST 0 (None)
……
=================================================================
>>> import math
>>> exec "f=math.log(100,10)"
>>> print f
2.0
=================================================================
>>> import sys
>>> sys._getframe().f_globals.get("name", "<string>")
‘main‘
=================================================================
load_module(‘os’, "O_EXCL O_CREAT O_RDWR".split())
def load_module(module_name, symbols):
module = import(module_name)
for symbol in symbols:
globals()[symbol] = getattr(module, symbol)
=================================================================
http://pleac.sourceforge.net/pleac_python/datesandtimes.html
date & time
>>> import time
>>> time.time()
1231913155.263829
>>> time.gmtime(time.time())
(2009, 1, 14, 6, 5, 48, 2, 14, 0)
>>> time.asctime(time.gmtime(time.time()))
‘Wed Jan 14 06:05:09 2009’
>>> time.ctime(time.time())
‘Wed Jan 14 14:08:49 2009’
>>> time.ctime()
‘Wed Jan 14 14:07:31 2009’
>>> time.sleep(3) # sleep 3 seconds
=================================================================
>>> import math
>>> math.sin(math.pi/2)
1.0
=================================================================
>>> import random # use help(random) to see the (large) list of funcs
>>> random.randint(1,100) # in range [1, 100]
93
>>> mylist
[1, 2, 100, 444, 200]
>>> random.choice(mylist)
200
>>> random.randrange(1, 100, 2) # range(start, stop[, step])
79
>>> mylist
[1, 2, 3, 4, 5, 5, 6, 6, 7, 8, 9, 10, 10]
>>> random.sample(mylist,4) # Chooses k unique random elements
[6, 5, 7, 2]
>>> random.shuffle(mylist)
>>> mylist
[6, 10, 3, 8, 2, 7, 5, 1, 6, 5, 9, 4, 10]
>>> random.gauss(100, 10)
103.22331244557154
=================================================================
>>> for i in range(1,10,2): print i,
1 3 5 7 9
>>> for i in range(1,10,2): print i
1
3
5
7
9
=================================================================
>>> a
[1, 2, 3]
>>> b
[‘j’, ‘f’, ‘o’]
>>> zip(a,b)
[(1, ‘j’), (2, ‘f’), (3, ‘o’)]
cuts = [8, 14, 20, 26, 30]
pieces = [ theline[i:j] for i, j in zip([0]+cuts, cuts+[None]) ]
=================================================================
>>> import struct
>>> str
‘123451231234567887654321’
>>> len(str)
24
>>> fmt
‘5s 3x 8s 8s’
>>> struct.calcsize(fmt)
24
>>> struct.unpack(fmt, str)
(‘12345’, ‘12345678’, ‘87654321’)
=================================================================
>>>quest = rawinput("What is your quest? ")
What is your quest? To seek the holy grail.
>>>quest
‘To seek the holy grail.’
=================================================================
>>> import itertools
>>> L = [1,2,3,4]
>>> for item in itertools.ifilter(L. contains _, [1,3]):
>>> print "yes", item
yes 1
yes 3
=================================================================
import codecs
# Open a UTF-8 file in read mode
infile = codecs.open("infile.txt", "r", "utf-8")
# Read its contents as one large Unicode string.
text = infile.read()
# Close the file.
infile.close()
=================================================================
>>> u’你好’.encode(‘gb2312’)
‘xc4xe3xbaxc3’
>>> ‘你好’.decode(‘gb2312’).encode(‘utf8’)
‘xe4xbdxa0xe5xa5xbd’
try:
unicode(value, "ascii")
except UnicodeError:
value = unicode(value, "utf-8")
else:
# value was valid ASCII data
pass=================================================================
>>> str
‘jfo’
>>> print map(ord, str)
[106, 102, 111]
>>> r
[‘j’, ‘f’, ‘o’]
>>> import operator
>>> lstr=reduce(operator.add, r, "+")
>>> lstr
‘+jfo’
=================================================================
>>> print ‘|’, ‘hej’.ljust(20), ‘|’, ‘hej’.rjust(20), ‘|’, ‘hej’.center(20), ‘|’
| hej | hej | hej |
>>> print ‘hej’.center(20, ‘+’)
++++++++hej+++++++++
=================================================================
>>> import time
>>> print time.strftime(‘%Y-%m-%d-%S’)
2008-12-15-00
=================================================================
调用glibc中的 prctl函数,改变当前进程的进程名
import dl
libc = dl.open(‘/lib/libc.so.6′)
libc.call(‘prctl’, 15, ‘ubuntu-tweak’, 0, 0, 0)
=================================================================
>>> print ord(‘a’)
97
>>> print chr(97)
a
>>> print ord(u’u2020’)
8224
>>> print repr(unichr(8224))
u’u2020’
>>> ‘abcdefg’.replace(‘abc’, ‘jfo’)"jfodefg"
>>> import string
>>> table = string.maketrans(string.ascii_lowercase, string.ascii_lowercase[2:]+string.ascii_lowercase[:2])
### translate(s,table [,deletions]) -> string
>>> string.translate("abc", table)
‘cde’
>>> string.translate("abcde", table, "ac")
‘dfg’
=================================================================
>>> string.zfill("abc",8)
‘00000abc’
=================================================================
lstrip、rstrip、strip
>>> x = ‘xyxxyy hejyx yyx’
>>> print ‘|’+x.strip(‘xy’)+’|’
| hejyx |
=================================================================
>>> print ‘one tWo thrEe’.capitalize( )
One two three
>>> print ‘one tWo thrEe’.title( )
One Two Three
=================================================================
pprint.pprint : pretty print
>>> pprint.pprint(stuff)
[<Recursion on list with id=869440>,’’,’/usr/local/lib/python1.5’,’/usr/local/lib/python1.5/test’,’/usr/local/lib/python1.5/sunos5’,’/usr/local/lib/python1.5/sharedmodules’,=================================================================Debug-mode variables
Setting these variables only has an effect in a debug build of Python, that is, if Python was configured with the –with-pydebug build option.
- PYTHONTHREADDEBUG
If set, Python will print threading debug info.
Changed in version 2.6:Previously, this variable was called THREADDEBUG.
- PYTHONDUMPREFS
- If set, Python will dump objects and reference counts still alive after shutting down the interpreter.
- PYTHONMALLOCSTATS
- If set, Python will print memory allocation statistics every time a new object arena is created, and on shutdown.