1)列表逆序,字符串逆序
l[::-1]
l.reverse() #list
2)三元操作符
x if x>y else y
(x>y and [x] or [y])[0]
3)阶乘
f=lambda n:reduce(lambda x,y:x*y,range(1,n+1))
4)sort,sorted
sorted(L, cmp=lambda x,y:cmp(x[1],y[1]))
sorted(L, key=lambda x:x[1]))
sorted(L, key=operator.itemgetter(1,2))
sorted(L, key=operator.attrgetter('name1','name2'))
sorted([5, 2, 3, 1, 4], reverse=True)
5)递归限制
sys.getrecursionlimit()
sys.setrecursionlimit(n)
6) 编码
默认unicode

# -*- coding: utf-8 -*-
#coding=utf-8
#coding:utf-8
sys.setdefaultencoding('utf8')

try:
printl.decode('utf8').encode('gbk')
except UnicodeEncodeError:
pass

7)读取命令行输入
a)for l in sys.stdin
b)try:
l=raw_input()
exceptEOFError:
pass

8)二进制,十进制,十六进制转换
'%x'%232
hex(232)
eval('0xe8')
int('e8',16)
string.atoi(s[,base])
bin(),int(),oct(),hex()
int('0111',2),eval('0b0111')
''.join([str((number>>a&0x1))for a in range(7,-1,-1)])

9)列表转字符串
''.join(list)

10)错误处理
try:
block;
except [Exception[,e]]:
block;
[except [exception]]
else:
block;

try:
;
except ...
;
finally:
;

11)dict合并
dict(d1.items()+d2.items())
dict(d1,**d2)
tmp=d1.copy();tmp.update(d2)

12)list转置
[[row[col] for row in arr] for col in range(len(arr[0]))]
map(list, zip(*arr))

13)生成器
def fun():
  for i in range(10):
    n=(yield i)
  return
#如果当调用next方法时生成器函数结束(遇到空的return语句或是到达函数体末尾),则这次next方法的调用将抛出StopIteration异常(即for循环的终止条件)

r=fun()
r.next() #next(r)
r.send(10)
r.throw(type, value=None, traceback=None) #在生成器内部(生成器的当前挂起处,或未启动时在定义处)抛出一个异常。

14)slice
>>> a = [0, 1, 2, 3, 4, 5]
>>> LASTTHREE = slice(-3, None)
>>> a[LASTTHREE]
[3, 4, 5]
itertools.islice()

15)相邻项分组

a)
>>> a = [1, 2, 3, 4, 5, 6]
>>> zip(*([iter(a)] * 2))
[(1, 2), (3, 4), (5, 6)]
>>> group_adjacent = lambda a, k: zip(*([iter(a)] * k))
>>> group_adjacent(a, 3)
[(1, 2, 3), (4, 5, 6)]
b)
>>> zip(a[::2], a[1::2])
[(1, 2), (3, 4), (5, 6)]
>>> group_adjacent = lambda a, k: zip(*(a[i::k] for i in range(k)))
>>> group_adjacent(a, 3)
[(1, 2, 3), (4, 5, 6)]

*逆向,展平二维数组

[j for i in a for j in i]

itertools.chain(*a)

16)unpack

import struct
# 取前5个字符,跳过4个字符,再取3个字符
format = '5s 4x 3s'
print struct.unpack(format, 'Test astring')
#('Test', 'ing')

17)inspect查看源码

>>> from collections import namedtuple
>>> import inspect; print(inspect.getsource(namedtuple))
>>> import cinspect; print(cinspect.getsource(input))

18)字符串格式

>>> print "Hello %(name)s !" % {'name': 'James'}
>>> print "Hello {name} !".format(name="James")
>>> print "Hello {0} !".format("James")
 
 19)print 输出重定向
print >> open("somefile", "w+"), "Hello World"
 
20)删除切片
a[1:4]=[]
del a[::2]
 
21)isinstance
>>> isinstance(1, (float, int))
>>> isinstance(1.3, (float, int))
>>> isinstance("1.3", (float, int,str))
 
22)字符串转变量
exec('abc = 5')
globals()['abc'] = 6
setattr(__builtins__, 'abc', 9)
__import__('sys')._getframe(0).f_globals['abc'] = 27
 
23)动态import
m=__import__(modu)
m=imp.loadmodule(modu,*imp.findmodule(modu))
m=importlib.importmodule(modu)
getattr(m,function|class name)
new.instance(class)
 
24)print raw 字符串
repr(a)[1:-1]
 
25)格式输出list,dict
print json.dumps(list,indent=4)
 
posted on 2013-12-20 15:24  perel  阅读(311)  评论(0编辑  收藏  举报