Oct 4, 2008

Learning python 读书笔记(6, 7章)

Chapter 6: Lists and Dictionaries
1. List
Methods: grow, sort, search, reverse, append, extend, append
del L[x:y], L[x:y]=[a,b,c]
range(x), xrange(x,y), L.pop()
2. List in Action
Slice assignment: delete + insert
L.append(x) < -- > L+[x]
3. Dictionaries
D.keys(), D.values(), D.items():
create a new list
D.copy(), D.get(k, default),
D2.update(D1): merges the keys and values of one directory into another, blindly overwriting values of the same key.
D.has_key(k), k in D
D = dict(zip(keyslist, valueslist))
4. Dictionaries in Action
sequence operation don’t work.
Assigning to new indexes adds entries.
keys need not always be strings.(can be other immutable object)
Using dictionaries to simulate flexible lists Using dictionaries for sparse data structures
Matrix = {}
Matrix[(2,3,4)] = 88: the number at position (2,3,4) is 88
Using dictionaries as “reconds”
Dictionary interfaces
import anydbm
file = anydbm.open(“filename”)
file [‘key’] = ‘data’ #store data by key
data = file[‘key’] #fetch data by key

Chapter 7: Tuples, Files, and Everything Else
1. Tuples

simple groups of objects, cannot change in place(immutable), don't support any method calls
>>> (1,2) + (3,4)
(1, 2, 3, 4)
>>> (1,2) * 3
(1, 2, 1, 2, 1, 2)
>>> T = ('1', '2', '3')
>>> tmp = list(T)
>>> tmp
['1', '2', '3']
>>> T2 = tuple(tmp)
>>> T2
('1', '2', '3')
>>> T = (1, [2,3], 4)
>>> T[1][0] = 5 #works
>>> T[0] = 0 #Fails
2. Files
input = open('path', 'r'), output = open ('path', 'w')  #mode: r, w, a
S = input.read(), S = input.read(N) # N bytes
S = input.readline(), S = input.readlines()
output.write(S), output.writelines(L), output.close()
seek: reset current position in file, flush: buffered output write into disk
3. Type Categories Revisited
Operator Overloading:

class MySquence:
    def __getitem__(self, index):
        #called on self[index]
    del __add__(self, other):
        #called on self + other
4. Object Generality
Lists, dictionaries, and tuples can: 1. hold any kind of object 2. arbitrarily nested
Lists and dictionaries can dynamically grow and shrink.
5. References Versus Copies
No reference to the same object:

A = L[:]    #instead of: A = L (or list(L))
B = D.copy()    #instead of: B = D
empty-limit slices and copy method only do a top-level copy!
nested copy:
import copy
X = copy.deepcopy(Y)
6. Comparisons, Equality, and Truth
L1 == L2, L1 is L2    #Equivalent? Same object?
But short string: S1 = 'spam', S2 = 'spam' # S1==S2: true, S1 is S2: true
Numbers are true if nonzero
Other objects are true if nonempty
None: much like NULL in C
L = [None] * 100
bool: True, False

0 comments: