[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

A database list


Of course, what we’ve really coded so far is just two variables, not a database; to collect
Bob and Sue into a unit, we might simply stuff them into another list:


>>> people = [bob, sue] # reference in list of lists
>>> for person in people:
print(person)

['Bob Smith', 42, 30000, 'software']
['Sue Jones', 45, 50000.0, 'hardware']

Now the people list represents our database. We can fetch specific records by their
relative positions and process them one at a time, in loops:


>>> people[1][0]
'Sue Jones'

>>> for person in people:
print(person[0].split()[-1]) # print last names
person[2] *= 1.20 # give each a 20% raise

Smith
Jones

>>> for person in people: print(person[2]) # check new pay

36000.0
60000.0

Now that we have a list, we can also collect values from records using some of Python’s
more powerful iteration tools, such as list comprehensions, maps, and generator
expressions:


>>> pays = [person[2] for person in people] # collect all pay
>>> pays
[36000.0, 60000.0]

>>> pays = map((lambda x: x[2]), people) # ditto (map is a generator in 3.X)
>>> list(pays)
[36000.0, 60000.0]

>>> sum(person[2] for person in people) # generator expression, sum built-in
96000.0

To add a record to the database, the usual list operations, such as append and extend,
will suffice:


>>> people.append(['Tom', 50, 0, None])
>>> len(people)
3
>>> people[-1][0]
'Tom'

Lists work for our people database, and they might be sufficient for some programs,
but they suffer from a few major flaws. For one thing, Bob and Sue, at this point, are


6 | Chapter 1: A Sneak Preview

Free download pdf