Python Xiaozhan _07: Python Other built-in functions and document processing

Today learned:

 

First, the other built-in functions

1, zip Usage: The sequence of elements in series, one-

Note: zip has two parameters, both for the sequence, you need one correspondence

a={"name":"apple","age":"18","gender":"male"}
print(list(zip(a.keys(),a.values())))

>>>[('name', 'apple'), ('age', '18'), ('gender', 'male')]

b
=("12345","hello") print(list(zip("12345","hello")))

>>>[('1', 'h'), ('2', 'e'), ('3', 'l'), ('4', 'l'), ('5', 'o')]

 

2, max and min of usage: Find the maximum and minimum.

max advanced application: 
age_li
= { " Apple " : 16 , " Banana " :. 19 , " CAT " : 34 is , " Dog " : 70 } Print (max (age_li)) --- >> if the direct way, the print key is the maximum value of the dictionary Print (max (ZIP (age_li.values (), age_li.keys ())

Note: max the parameters required for the iterables, in turn from the first position for the cycle to begin, find the greatest after it is no longer looking back.
1, max is a function of the iterative process the object, a for loop corresponding to the amount withdrawn inside each element is compared, note: can not be compared among different data types;
2, comparing each element from each element the first starting position, and if this position is separated size, without the need for the latter to compare.

a=["a12","a43","c23"]

print(max(a))

c=[
    {"name": "apple", "age": 100},
    {"name": "banana", "age": 45},
    {"name": "cat", "age": 56},
    {"name": "gog", "age": 19},

]

print(max(c,key=lambda dic:dic["age"]))

>>>{'name': 'apple', 'age': 100}

 

3, slice usage: slice, corresponding to [n: m] slices

l=[1,3,5,7]
s1=slice(2,5)
print(l[s1])

 

4, sorted Usage: row order, is a comparison of the size of the essence. Can not be compared among different data types

c=[
    {"name": "apple", "age": 100},
    {"name": "banana", "age": 45},
    {"name": "cat", "age": 56},
    {"name": "gog", "age": 19},
]
print(sorted(c,key=lambda dic:dic["age"]))

>>>[{'name': 'gog', 'age': 19}, {'name': 'banana', 'age': 45}, {'name': 'cat', 'age': 56}, {'name': 'apple', 'age': 100}]

 

5, sum Usage: summation. After the parameter is iterables.

= L [1,2,3,4 ]
 Print (SUM (L))
 Print (SUM (Range (101))) ----> can be calculated from 1 to 100 and

 

6, type Usage: View data types, can be used in the program to make a judgment, according to different data types and perform different logic.

msg="123"
if type(msg) is str:
    msg=int(msg)
    res=msg+1
    print(res)

 

7, import Usage: call other modules py file, just enter the file name (without .py), Note: You can not string

import text
text.say_hi()
__import__ ( " text " ) ---> This can be imported str. 

ps: In the bottom of the computer actual call is _import_ ().

 

Second, document processing

(A) file processing workflow

The computer system is divided into: three parts, computer hardware, operating systems, applications.

We use python or applications written in other languages ​​if you want to put down permanent preservation of data must be stored in the hard disk, which involves the application to operate the hardware is well known, the application can not access the hardware directly, which use to the operating system. Operating system, the complex hardware manipulation packaged into a simple interface to the user / application uses, wherein the file is an operating system to the application program operates the hard disk virtual concept, the user or application program by operating the file, can be their own data permanently preserved .

With the concept of files, we do not need to go to consider details of the operation of the hard drive, just need to focus on the process of file operations:

1. Open the file, get the file handle and assigned to a variable
2. Follow through on file handles
3. Close the file
Form: file handle = open ( 'file path', 'mode')
Open = F ( " text.py " , " R & lt " , encoding = " UTF8 " ) ---> to give filehandle
Data = reached, f.read () ---> assigned to a variable
 Print (Data) ---> and read operations are
f.close () ---> Close File

Note: Open a resource file contains two parts: variable operating system-level open file + application.
When a file operation is completed, the ground must be recovered and not a part of the resources of the two file recovery method as follows:
. 1, f.close () # file level to open the recovery operating system 
2, del F # recycle the application level variable

Which del f must occur after f.close (), which would otherwise cause the operating system to open the file has not been closed, in vain footprint,
The python automatic garbage collection mechanism determined that we need to consider del f, but after the operation is completed the file, we must remember f.close ()

Open with ( " text.py " , " R & lt " , encoding = " UTF8 " AS F: ---> can be used instead of closing the file with the operation, without close operation
     pass
with open("a_py","r") as read_f,open("b_py","w") as write_f:  --->可打开多个文件
    data=read_f.read
    wirte_f.write(data)

 

(B) open and file

In python3 only open ()

There are open () and file () in the python2

Note: file type file; a file () to open a file, the file is a configuration corresponding to that class. And () to open the file open, with built-in function to operate python. General use open.

 

(C) read-only, write-only, append

r, [read-only mode the default mode, the file must exist, there is no exception is thrown]

w, write-only mode [unreadable; does not exist, create an empty document; it exists to empty the contents]

a, the additional write mode [unreadable; does not exist, create an empty document; there is only the additional content]

r +, [reader readable, writable]

w +, W R {read, write}

a +, [read write read, write}

reached, f.read () # read all of the content, move the cursor to the end of the file 
f.readline () # read a single line, the cursor moves to the second row header 
f.readlines () # read each row of content, stored in the list
f.readable() #文件是否可读
f.writable() #文件是否可读
f.write('1111\n222\n') #针对文本模式的写,需要自己写换行符 
f.write('1111\n222\n'.encode('utf-8')) #针对b模式的写,需要自己写换行符
f.writelines(['333\n','444\n']) #文件模式
f.writelines([bytes('333\n',encoding='utf-8'),'444\n'.encode('utf-8')]) #b模式

 

with open("text.py","r",encoding="utf8") as f:
    print(f.readable())
    print(f.read())
    print(f.readlines())

f=open("text.py","w",encoding="utf8")
data=f.write("1234545656\n")---->写入行,用str,记得用换行符隔开
f.close()

f=open("text.py","w",encoding="utf8")
data=f.writelines(["1234545656\n","yidsaksfhsak\n","ashdihifhih\n"])--->写多行时要用列表形式写入
f.close()


f=open("text.py","a",encoding="utf8")
data=f.writelines(["1234545656\n","yidsaksfhsak\n","ashdihifhih\n"])--->追加写在文件的最后,追加就相当于写,可调用write的函数
f.close()


with open("text.py","r") as read_f,open("text.py","w") as write_f:   --->以这种方式把文件既打开读模式,又打开写模式,即可对文件进行覆盖(修改即覆盖)
data=read_f.read()
write_f.write("sdhfdshgkjsdhgh\n")

  

以上。

Guess you like

Origin www.cnblogs.com/211293dlam/p/12469216.html