笨办法学Python记录--习题38-40,复习前面,运用list操作函数

#习题38 区分列表和字符串,用到了split(字符串专用函数),join、append、pop(这些是list操作函数)

 1 ten_things = "Apples Oranges Crows Telephone Liht Sugar"
 2 
 3 print "Wait there is not 10 things in that list, let's fix that."
 4 
 5 stuff=ten_things.split(' ')
 6 
 7 more_stuff = ["Day","Night","Song","Frisbee","Corn","Banana","Girl","Boy"]
 8 
 9 while len(stuff)!=10:
10 next_one = more_stuff.pop()
11 print "Adding:",next_one
12 stuff.append(next_one)
13 print "There's %d items now." % len(stuff)
14 
15 print "There we go:",stuff
16 print "Let's do some things with stuff."
17 
18 print "stuff[1]"
19 print stuff[1]
20 
21 print "stuff[-1]"
22 print stuff[-1]
23 
24 print "stuff.pop()"
25 print stuff.pop()
26 
27 print "' '.join(stuff)"
28 print ' '.join(stuff)
29 
30 print "'#'.join(stuff[3:5]"
31 print '#'.join(stuff[3:5]
32 
33 )

 

结果:

#习题38 区分列表和字符串,同时学者使用split函数
ten_things = "Apples Oranges Crows Telephone Liht Sugar"

print "Wait there is not 10 things in that list, let's fix that."

stuff=ten_things.split(' ')

more_stuff = ["Day","Night","Song","Frisbee","Corn","Banana","Girl","Boy"]

while len(stuff)!=10:
next_one = more_stuff.pop()
print "Adding:",next_one
stuff.append(next_one)
print "There's %d items now." % len(stuff)

print "There we go:",stuff
print "Let's do some things with stuff."

print "stuff[1]"
print stuff[1]

print "stuff[-1]"
print stuff[-1]

print "stuff.pop()"
print stuff.pop()

print "' '.join(stuff)"
print ' '.join(stuff)

print "'#'.join(stuff[3:5]"
print '#'.join(stuff[3:5]

)

 

个人觉得这么使用字典很帅很帅!!

 1 cities = {'CA':'San Francisco','MI':'Detroit','FL':'Jacksonville'}
 2 cities['NY']='New York'
 3 cities['OR']='Portland'
 4 
 5 def find_city(themap,state):
 6     if state in themap:
 7         return themap[state]
 8     else:
 9         return "Not found."
10         
11 cities['_find'] = find_city
12 
13 while True:
14     print "State?(ENTER to quit)",
15     state = raw_input("> ")
16     
17     if not state:break
18     city_found = cities['_find'](cities,state)
19     print city_found

关于字典:字典出现在当索引不好用的时候--字典中的值并没有特殊的顺序,但是都存储在一个特定的键(key)里。key可以是数字、字符串甚至元组。

字典应用:1. 数字电话/地址簿;2. 存储文件修改次数,用文件名作为键;3. 表征游戏键盘的状态,每个键都是由坐标值组成的元组;

dict函数的使用:

>>>d=dict(name='GG', age=32)

>>>d

{'age':32,'name':'GG'}

or

>>>a=[('name','GG'),('age',42)]

>>>d=dict(a)

简单数据库实现:

 1 people = {'Alice':{'phone':'2341','addr':'Foo drive 23'},'Beth':{'phone':'9102','addr':'Bar steet 42'},'Cecil':{'phone':'3158','addr':'Baz avenue 90'}}
 2 labels = {'phone':'phone number','addr':'address'}
 3 name = raw_input('Name: ')
 4 request=raw_input('phone number(p) or address(a)?')
 5 if request=='p':
 6     key = 'phone'
 7 if request == 'a':
 8     key = 'addr'
 9 if name in people:
10     print "%s's %s is %s." % (name,labels[key],people[name][key])

深拷贝,浅拷贝

待续

posted on 2014-04-23 14:41  麦兜布熊  阅读(389)  评论(0编辑  收藏  举报