Programming Python - 1. Preview -1.1 Representing Records

1. using list

bob=['bob smith',  42, 3000, 'software']

sue=['sue jones', 45, 4000, 'hardware']


bob[0], sue[2]


bob[0].split()[-1]

split 默认以空格分隔

sue[2]*=1.25



people= [bob, sue]

for person in people:
    print(person)

people[1][0]

for person in people:
  print(person[1].split()[-1])
  person[2]*=1.2

for person in people: print(person[2])

pays=[person[2] for person in people]

pays=map( (lamba x: x[2]), people)

list (pays)

sum(person[2] for person in people)

people.append(['tom', 50, 0, None])
len(people)
people[-1][0]


bob=[ ['name', 'bob smith'], ['age', 42], ['pay', 4200]]
sue=[['name','sue jones'],['age',45']. ['pay', 4500]]

people=[bob, sue]

for person in people:
    for (name, value) in people:
        if name=='name': print(value)

def field(record, label):
    for (fname, fvalue) in record:
        if fname==label: 
            return fvalue

field(bob, 'name')
field(sue, 'pay')

for rec in people:
    print(field(rec, 'age'))

 

for person in people:
  print(person[1].split()[-1])
  person[2]*=1.2

for person in people: print(person[2])

pays=[person[2] for person in people]

pays=map( (lamba x: x[2]), people)

list (pays)

sum(person[2] for person in people)

people.append(['tom', 50, 0, None])
len(people)
people[-1][0]


bob=[ ['name', 'bob smith'], ['age', 42], ['pay', 4200]]
sue=[['name','sue jones'],['age',45']. ['pay', 4500]]

people=[bob, sue]

for person in people:
    for (name, value) in people:
        if name=='name': print(value)

def field(record, label):
    for (fname, fvalue) in record:
        if fname==label: 
            return fvalue

field(bob, 'name')
field(sue, 'pay')

for rec in people:
    print(field(rec, 'age'))

2. Using Dictionary

bob={'name': 'bob smith', 'age': 42, 'pay':30000, 'job':'dev}
sue={'name': 'sue jones', 'age':45,'pay':40000,'job':'hdw'}

bob[name], sue[pay]

#another way to make dictionary
bob=dict(name='bob smith', age=42, pay=30000, job='dev')
sue=dict(name='sue jones', age=45, pay=40000, job='hdw')

#another way to make dictionary also
sue={}
sue['name']='sue jones'
sue['age']=45
sue['pay']=40000
sue['job']='hdw'


sue

#another way to make dictionary from keys
fields=('name', 'age', 'job'. 'pay')

records=dict.fromkeys(fields, '?')



###dictionary of dictionary

bob={'name': 'bob smith', 'age': 42, 'pay':30000, 'job':'dev'}
sue={'name': 'sue jones', 'age':45,'pay':40000,'job':'hdw'}

db={}
db['bob']=bob
db['sue']=sue

db

import pprint
pprint.pprint(db)

#Iteration in db is iteration on keys
for keys in db:
    print(key, "=>", db[key]['name'])

#iteration on dictionary's valuse
for record in db.values(): print(record['pay']

 

 

 

posted @ 2014-02-22 10:58  yjjsdu  阅读(236)  评论(0)    收藏  举报