Python notes (6): Derivation data, python notes derivation data
(1) Preparations
Create a file to record the athlete's running score
James.txt
2-34,3: 21, 2.34, 2.45, 3.01, 2-22
(2) Requirements
Output the best scores of athletes on the screen.
(3) how to implement it
(1) create a file object through open ()
(2) read file data through the open () readline method (this output is a row of data)
(3) If you want to obtain the best three scores, you must first split the data (split the scores by split)
(4) sort the split List Data
(5) inconsistencies in symbols between 2-2.34, 3: 21, and may cause sorting problems (-and, and.). Therefore, a function is required to change them to the same one.
(4) specific implementation
(1) Main program code
from FirstPython import the_list as tl
#Import the_list Module
The_james = tl. dsfile ('F: \ PythonFile \ james.txt')
#Call the dsfile () function of the_list module to read file data.
Print (sorted (set ([tl. sanitize (t)ForTInThe_james]), reverse =True) [0: 3])
# Sorted ()Sort in ascending order by default. If reverse is set to True, sort in descending order.
# Set () delete duplicate items and return new set objects (unordered)
# [0: 3]Data of 0th, 1st, and 2nd items in the access list
'''
[Tl. sanitize (t) for t in the_james]Equivalent to the following code (iterative processing of the_james list, returns a new list)
New_list = []
For t in the_james:
New_list.append (tl. sanitize (t ))
'''
(2) the_list module code
DefSanitize (time_str ):
#Input data, change '-' and ':' To '.', and return. Otherwise, return directly.
If'-'InTime_str:
(X, y) = time_str.split ('-', 1)
Return(X +"."+ Y)
Elif':'InTime_str:
(X, y) = time_str.split (':', 1)
Return(X +"."+ Y)
Else:
Return(Time_str)
DefDsfile (the_file ):
#Input a file and return the first line of data of the file.
WithOpen (the_file)AsJames_file:
Each_line = james_file.readline (). strip (). split (',')
# Strip ()Removes unnecessary blank characters in the string. If this list is not added, one \ n is added.
# Split (',') Splits data according to and returns a list
ReturnEach_line