1 def init(data):
2 data['first'] = {}
3 data['middle'] = {}
4 data['last'] = {}
5
6 def lookup(data, label, name):
7 return data[label].get(name)
8
9 def store(data, full_name):
10 names = full_name.split()
11 if len(names) == 2:
12 names.insert(1, '')
13 labels = 'first', 'middle', 'last'
14 for label, name in zip(labels, names):
15 people = lookup(data, label, name)
16 if people:
17 people.append(full_name)
18 else:
19 data[label][name] = [full_name]
20
21 my_names = {}
22 init(my_names)
23 store(my_names, 'Magnus Lie Hetland')
24 print(my_names)
25 print(lookup(my_names, 'middle', 'Lie'))
26
27 store(my_names, 'Robin Hood')
28 store(my_names, 'Robin Locksley')
29 print(my_names)
30 print(lookup(my_names, 'first', 'Robin'))
31 store(my_names, 'Mr. Gumby')
32 print(my_names)
33 print(lookup(my_names, 'middle', ''))
34
输出:
>>>
{'middle': {'Lie': ['Magnus Lie Hetland']}, 'first': {'Magnus': ['Magnus Lie Hetland']}, 'last': {'Hetland': ['Magnus Lie Hetland']}}
['Magnus Lie Hetland']
{'middle': {'': ['Robin Hood', 'Robin Locksley'], 'Lie': ['Magnus Lie Hetland']}, 'first': {'Robin': ['Robin Hood', 'Robin Locksley'], 'Magnus': ['Magnus Lie Hetland']}, 'last': {'Hetland': ['Magnus Lie Hetland'], 'Locksley': ['Robin Locksley'], 'Hood': ['Robin Hood']}}
['Robin Hood', 'Robin Locksley']
{'middle': {'': ['Robin Hood', 'Robin Locksley', 'Mr. Gumby'], 'Lie': ['Magnus Lie Hetland']}, 'first': {'Mr.': ['Mr. Gumby'], 'Robin': ['Robin Hood', 'Robin Locksley'], 'Magnus': ['Magnus Lie Hetland']}, 'last': {'Hetland': ['Magnus Lie Hetland'], 'Locksley': ['Robin Locksley'], 'Gumby': ['Mr. Gumby'], 'Hood': ['Robin Hood']}}
['Robin Hood', 'Robin Locksley', 'Mr. Gumby']
改进:利用收集参数,一次可以添加多个名字 strage_2
1 def init(data):
2 data['first'] = {}
3 data['middle'] = {}
4 data['last'] = {}
5
6 def lookup(data, label, name):
7 return data[label].get(name)
8
9 def store(data, full_name):
10 names = full_name.split()
11 if len(names) == 2:
12 names.insert(1, '')
13 labels = 'first', 'middle', 'last'
14 for label, name in zip(labels, names):
15 people = lookup(data, label, name)
16 if people:
17 people.append(full_name)
18 else:
19 data[label][name] = [full_name]
20
21 def store_2(data, *full_names):
22 for full_name in full_names:
23 names = full_name.split()
24 if len(names) == 2:
25 names.insert(1, '')
26 labels = 'first', 'middle', 'last'
27 for label, name in zip(labels, names):
28 people = lookup(data, label, name)
29 if people:
30 people.append(full_name)
31 else:
32 data[label][name] = [full_name]
33
34 my_names = {}
35 init(my_names)
36 store(my_names, 'Magnus Lie Hetland')
37 print(my_names)
38 print(lookup(my_names, 'middle', 'Lie'))
39
40 store(my_names, 'Robin Hood')
41 store(my_names, 'Robin Locksley')
42 print(my_names)
43 print(lookup(my_names, 'first', 'Robin'))
44 store(my_names, 'Mr. Gumby')
45 print(my_names)
46 print(lookup(my_names, 'middle', ''))
posted on 2013-05-16 20:12
unixfy 阅读(227)
评论(0) 编辑 收藏 引用