(a) brief description
A dictionary is a python built-in data structure that associates data with keys (for example: Name: Zhang San, name is key, Zhang San is data). For example: The following is a dictionary
{' name ': ' Zhang San ', ' Date of birth ': ' 2899-08-12 ', ' score ': [' 3.21 ', ' 3.10 ', ' 3.01 ']}
Create dictionaries, add data, and access dictionary data in the following ways:
D = {} # Create dictionary directly with {}
f = dict ()# Create a dictionary from the factory function Dict ()
#通过下面的方式添加数据
d[' name '] = ' Zhang San '
d[' date of birth '= ' 2899-08-12 '
d[' scores '] = [' 3.21 ', ' 3.10 ', ' 3.01 ', ' 2.45 ', ' 2.34 ', ' 2.22 ', ' 2.01']
Print (d)
# access the dictionary data by key
Print (d[' name '])
Print (d[' Birth date ')
Print (d[' score '])
Print (d[' score '][2])
The output is as follows:
(ii) Convert the list to a dictionary
(1) Create a file
James2.txt The first item is the name, the second is the date of birth, followed by the result
James lee,2002-3-14,2-34,3:21,2.34,2.45,3.01,2:01,2:01,3:10,2-22,2-01,2.01,2:16
(2) Requirements
Output a dictionary of the following format on the screen
{' name ': ' James Lee ', ' Date of birth ': ' 2002-3-14 ', ' score ': [' 3.21 ', ' 3.10 ', ' 3.01 ']}
(3) Main program code
Td
The_james2 = td.chdict (' F:\Python\Python file \james2.txt ')
Print (The_james2)
(4) The_dict module code
defSanitize (TIME_STR):
#Pass in the string and change '-' and ': ' to '. ' and return, or return directly
if'-'inchTIME_STR:
(x, y) = Time_str.split ('-', 1)
return(x+"."+y)
elif': 'inchTIME_STR:
(x, y) = Time_str.split (': ', 1)
return(x +"." + y)
Else:
return(TIME_STR)
defChdict (The_file):
#Pass in the file, return a dictionary
D = dict ()
withOpen (The_file) asJames_file:
The_list = James_file.readline (). Strip (). Split (', ')
#split data, return a list
d['name '] = The_list.pop (0)
#pop ()deletes the data item at the specified location and returns
d['date of birth '] = The_list.pop (0)
d['Results '] = sorted (Set ([Sanitize (t) forTinchThe_list]), reverse=True) [0:3]
#set ()Delete duplicate data and return an unordered collection, sorted () sort
returnD
(iii) class, attribute, object instance
Simply put, classes and attributes are an abstract concept, and object instances are a concrete "presence." For example:
Class: People
Properties: Name, height, weight
Object instances: Zhang San, John Doe
A person refers to a kind of things, height, name, weight is the property of such things, Zhang San, John Doe refers to a specific person.
(iv) Creating a class, creating an object instance
People:
__init__ (self):
Description: This part of the above is necessary, where people is the class name, its own custom, the __init__ (self) method controls how the object is initialized, which is also required (this is a target identifier that identifies what the current object is specifically)
As an example:
(1) Create a class
class People:
def __init__ (self,name,date=None, achievement=[]):
# Date , Achievement has default (default) value
Self.name = Name
Self.date = Date
Self.achievement = Achievement
(2) Creating an object instance
ZS = People (' Zhang San ')
# create an object instance with name Zhang San
Description: When using ZS = people (' Zhang San '), the __init__ () method of the People class is automatically called, where self = zs,name= ' Zhang San ' and then create a name = ' Zhang San ' date= None, achievement=[] object instance ZS
(3) Many methods can be defined in a class, but the first argument of each method must be self (without setting this argument, the first parameter is treated as the self parameter).
For example:
Chdict (Self,the_file):
New_file:
The_list = New_file.readline (). Strip (). Split (', ')
People (The_list.pop (0), The_list.pop (0), the_list)
TOP3 (self):
returnself.achievement), reverse=True) [0:3])
(v) Succession
You can create a new class from scratch, or you can inherit a class that has already been created, adding properties and methods to that base.
The concept of inheritance: inherit all the methods and properties of the parent class, the subclass can add new methods, properties, or the methods of the parent class can be overridden. Simply put, for example, if you inherit all of your father's abilities and talents (including height, weight, etc.), then you can learn to master more abilities, inherit from your father's ability and you can change according to your own needs (such as: excellent communication skills, your father may use in business negotiations, you may want to use on the girls). Metaphor may not be very image, please forgive me.
(1) Create a class in an inherited way
class Peoplelist (list):
def __init__ (self):
LIST.__INIT__ ([])
Peoplelist (list) The new class derives from the list class, list.__init__ ([]) initializes the derived class
(2) For example, the following class can inherit all the methods of the list
Peoplelist (list):
__init__ (self,name,date=None, achievement=[]):
LIST.__INIT__ ([])
Self.name = Name
Self.date = Date
Self.extend (Achievement)
You can test in the editor:
James = Peoplelist (' James ')
James.append (5)
Print (James)
James.extend ([i])
Print (James)
Python notes (vii): Dictionaries, classes, attributes, object instances, inheritance