Python Code snippet

(1)函数默认参数

def foo3 (i, L=[]):
    if len(L)==0:
        L.append(0)
    L[0]+=i
    return L[0]

print foo3(1)
print foo3(2)
print foo3(3)
print foo3(4)
 
上述代码得到的结果是
1
3
6
10

因此不要用可变对象作为默认参数值(Don’t use mutable as defaults)

1
2
3
4
def function(x, l=[]):              # 不要这么干
def function(x, l=None):        # 更好的一种方式
    if l is None:
       l = []

 

 

 

 

 tca , tcb , tcc 差异

class tc:
    tca = []
    tcb = ''
    def __init__(self,ff): 
        self.tcc = []
       

 

(2) Python中 set 相关操作

          python的set 是一个无序不重复元素集, 基本功能包括关系测试和消除重复元素.

          集合对象还支持union(联合), intersection(交), difference(差)和sysmmetric difference(对称差集)等数学运算.

         作为一个无序的集合,set 不记录元素位置或者插入点。因此,set 不支持 indexing, slicing, 或其它类序列的操作。

          基本操作:

 
len(s)         set 的长度
x in s          测试 x 是否是 s 的成员
x not in s   测试 x 是否不是 s 的成员
s.issubset(t)
s <= t         测试是否 s 中的每一个元素都在 t 中
s.issuperset(t)
s >= t         测试是否 t 中的每一个元素都在 s 中
s.union(t)
s | t             集合的并
s.intersection(t)
s & t           集合的交
s.difference(t)
s - t            差集
s.symmetric_difference(t)
s ^ t           对称差集
s.copy()     浅复制
 

s.update(t)
s |= t        
s.intersection_update(t)
s &= t
s.difference_update(t)
s -= t
s.symmetric_difference_update(t)
s ^= t

s.add(x)
s.remove(x)       删除元素 x, 如果不存在则引发 KeyError
s.discard(x)       如果存在元素 x, 则删除
s.pop()              删除并返回一个不确定元素, 为空则引发 KeyError
s.clear()            删除所有元素

#说明:非运算符版本的操作支持任何 iterable 对象,不仅限于set 

(3)列表,元组,字典 (List,Tuple,Dictionary)

 

两个变量的交换:

1
a, b = b, a

参数在切片操作中的步骤,如:

1
2
3
a = [1,2,3,4,5]
>>> a[::2# 以步长为2的增量迭代整个list对象
[1,3,5]
 一个特殊的例子 `x[::-1]`用来反转x的实用语法。 
1
2
>>> a[::-1]
 [5,4,3,2,1]

 

学习各种集合(learn the various collections)

python有各种各样的容器数据类型,在特定情况下选择python内建的容器如:list和dict。通常更多像如下方式使用: 

1
2
3
4
5
6
freqs = {}
for c in "abracadabra":
    try:
        freqs[c] += 1
    except:
        freqs[c] = 1

 

 

 

 

 

另外一种方式: 

1
2
3
freqs = {}
   for c in "abracadabra":
       freqs[c] = freqs.get(c, 0) + 1

 使用defaultdict

1
2
3
4
from collections import defaultdict
freqs = defaultdict(int)
    for c in "abracadabra":
        freqs[c] += 1

其它集合 

1
2
3
4
5
namedtuple()       # 用指定的域创建元组子类的工厂函数
deque            # 类似list的容器,快速追加以及删除在序列的两端
Counter          # 统计哈希表的dict子类
OrderedDict            # 记录实体添加顺序的dict子类
defaultdict            # 调用工厂方法为key提供缺省值的dict子类

 

 

 

 

(4)序列的特殊操作 filter , map , reduce , lambda

filter(function, sequence):对sequence中的item依次执行function(item),将执行结果为True的item组成一个List/String/Tuple返回:

#返回不能被2和3整除的数
>>> def f(x): return x % 2 != 0 and x % 3 != 0 
>>> filter(f, range(2, 25)) 
[5, 7, 11, 13, 17, 19, 23] 


map(function, sequence) :对sequence中的item依次执行function(item),见执行结果组成一个List返回:
>>> def cube(x): return x*x*x 
>>> map(cube, range(1, 11)) 
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000] 
>>> def add(x, y): return x+y 
>>> map(add, range(8), range(8)) 
[0, 2, 4, 6, 8, 10, 12, 14]


reduce(function, sequence, starting_value):对sequence中的item顺序迭代调用function 
>>> def add(x,y): return x + y 
>>> reduce(add, range(1, 11)) 
55 (注:1+2+3+4+5+6+7+8+9+10)
>>> reduce(add, range(1, 11), 20) 
75 (注:1+2+3+4+5+6+7+8+9+10+20)


lambda: 快速定义单行的最小函数,类似于C语言中的宏 
>>> g = lambda x: x * 2 
>>> g(3) 

>>> (lambda x: x * 2)(3) 
6


 (5)使用iteritems而不是items

iteriterms 使用的是 generators,所以当迭代很大的序列是此方法更好 

1
2
3
4
5
d = {1: "1", 2: "2", 3: "3"}
 
for key, val in d.items()       # 调用items()后会构建一个完整的list对象
 
for key, val in d.iteritems()   # 只有在迭代时每请求一次才生成一个值

 

 

 

 

 (6)使用isinstance 而不是type 

需要注意的是这里使用basestring而不是str是因为你可能会用一个unicode对象去检查是否为string,例如: 

1
2
3
4
5
>>> a=u'aaaa'
>>> print isinstance(a, basestring)
True
>>> print isinstance(a, str)
False

 

 

 

 

因为在Python中3.0以下的版本存在两种字符串类型str和unicode

        object
          |
       basestring
         / \
      str  unicode
posted @ 2012-05-23 19:58  Keosu  阅读(1652)  评论(0编辑  收藏  举报