6 Customizing Data Objects: Data structure customization
Packaging Code and data
Sarah2.txt:
Sarah sweeney,2002-6-17,2:58,2.58,2:39,2-25,2-55,2:54,2.18,2:55,2:55,2:22,2-21,2.22
Now to read the Sarah2.txt through the function get_coach_data () and complete the sort work, the code is as follows:
>>> sarah=get_coach_data (' Sarah2.txt ')
>>> (SARAH_NAME,SARAH_DOB) =sarah.pop (0), Sarah.pop (0)
>>> print (sarah_name+ "s fastest times is:" +str (Sorted (Set ([Sanitize (t) for T in Sarah])) [0:3])
Output: Sarah Sweeney ' s fastest times are:[' 2.18 ', ' 2.21 ', ' 2.22 '
It uses pop (0), which deletes and returns the first data item, and two pop (0) calls deletes the top two data values and copies them to the specified variable.
The above method is suitable for less data, if the amount of data is large, you need to introduce a dictionary association.
Associating data with a dictionary
A dictionary is a built-in data structure (built-in with Python) that allows data to be associated with a key, which is the same concept as a database key.
This makes the in-memory data consistent with the structure of the actual data, which may be referred to in other languages: mappings, hashes, associative arrays.
Note: Each dictionary has a name and a list of occupations lists.
There are two ways to create a dictionary:
One: Use curly braces to create;
such as: Cleese = {}
Second: Use the factory function to create;
such as: Palin =dict ()
In addition, you can use Type (Cleese), type (Palin) to view the type of the dictionary.
>>> cleese[' Name ']= ' John Cleese ' #创建Name列表
>>> cleese[' occuptions ']=[' actor ', ' comedian ', ' writer ', ' film producer '] #创建Occuptions列表
>>> palin={' Name ': ' Michael Palin ', ' occupations ': [' comedian ', ' actor ', ' writer ', ' TV ']} #创建字典内容, Be aware that the Palin dictionary is created at once.
>>> palin[' Name ']
' Michael Palin '
>>> cleese[' occuptions ']
[' actor ', ' comedian ', ' writer ', ' film producer ']
>>> cleese[' occuptions '][-1]
' film producer '
Next, add the birth address information to Palin and Cleese:
>>> palin[' birthplace ']= "Broomhill,sheffield,endland"
>>> cleese[' birthplace ']= "Weston-super-mare,north Somerset,england"
>>> Palin
{' Birthplace ': ' Broomhill,sheffield,endland ', ' occupations ': [' comedian ', ' actor ', ' writer ', ' TV '], ' Name ': ' Michael Palin '}
>>> Cleese
{' Birthplace ': ' Weston-super-mare,north somerset,england ', ' occuptions ': [' actor ', ' comedian ', ' writer ', ' film Producer '], ' Name ': ' John Cleese '}
Next, modify the method Get_coach_data () method to include the creation and use of the dictionary:
-------------------------------------------------------the End of sixth Chapter----------------------------------------------------
Python (Head first) study notes: Six