Python Cookbook notes

reduce

orig:

largeString = ''
for piece in pieces:
    largeString += piece

new:

import operator
largeString = reduce(operator.add, pieces, '')

new2:

largeString = ''.join(pieces)

Bound Method

example:

L = ['aa', 'bb', 'cc']
x = L.append  # append 是 list 的 method
x('dd')  # 等同使用 L.append('dd')
print(L)  # 此時 L 是 ['aa', 'bb', 'cc', 'dd']

another:

L = ['aa', 'bb', 'cc']
y = list.append # 指定 x 為 list 的 append method
y(L, 'dd') # 要指定作用對象是誰,要不無法作用
print(L)

handle list

example:

newlist1 = [x + 23 for x in oldlist]
newlist2 = [x for x in oldlist if x > 5]
newlist3 = [x + 23 for x in oldlist if x > 5]
L[:] = [min(x, 100) for x in L] # 將 L 中所有大於 100 的值,都設定成 100
a = [x+y+z for x in 'abc' for y in 'bcd' for z in 'cde']

shallow copy

example:

newlist = list(oldlist)
newdict = dict(olddict)

or:

import copy
newlist = copy.copy(oldlist)
newdict = copy.copy(oldlist)

deep copy

example:

import copy
newlist = copy.deepcopy(oldlist)
newdict = copy.deepcopy(olddict)

map

orig:

L1 = [f(x) for x in L]

map:

L1 = map(f, L)

sum

before python 2.4:

total = sum([x + 23 for x in thelist if x > 5])

after python 2.4:

total = sum(x + 23 for x in thelist if x > 5)

enumerate

orig:

for index in range(len(sequence)):
    if sequence[index] > 23:
        sequence[index] = transform(sequence[index])

enumerate:

for index, item in enumerate(sequence):
    if item > 23:
        sequence[index] = transform(item)

super

example:

class A():
    def __init__(self):
        print('enter A')
        print('leave A')

class B(A):
    def __init__(self):
        print('enter B')
        print('leave B')

B()

執行結果:

enter B
leave B

super:

class C(object):
    def __init__(self):
        print('enter C')
        print('leave C')

class D(C):
    def __init__(self):
        print('enter D')
        super(D, self).__init__()
        print('leave D')

D()

執行結果:

enter D
enter C
leave C
leave D

super2:

class E(D, C):
    def __init__(self):
        print('enter E')
        super(E, self).__init__()
        print('leave E')

E()

執行結果:

enter E
enter D
enter C
leave C
leave D
leave E

__getattr__

__setattr__

__str__

__repr__

內容目錄

上一個主題

Piston, Django REST API 產生器

下一個主題

簡易安裝 Trac 以及多國語系

本頁