Python basic study notes-some popular modules

Some popular modules

1、sys

The module sys allows you to access variables and functions closely related to the Python interpreter.

Function/variable Description
argv Command line parameters, including script name
exit([arg]) Exit the current program, you can specify the return value or error message through optional parameters
modules A dictionary that maps module names to loaded modules
path A list containing the name of the directory in which to find the module
platform A platform identifier, such as sunos5 or win32
stdin Standard input stream-an object similar to a file
stdout Standard output stream-an object similar to a file
stderr Standard error stream-a file-like object
[root@li python]# vim reverseargs.py
[root@li python]# cat reverseargs.py
import sys
args = sys.argv[1:]
args.reverse()
print(' '.join(args))
[root@li python]# python3 reverseargs.py this is a test
test a is this

2

The module os allows you to access multiple operating system services.

Function/variable Description
about Contains a map of environment variables
system(command) Execute operating system commands in a subshell
sep Separator used in the path
pathsep Separator to separate different paths
linesep Line separator ('\n','\r' or'\r\n')
urandom(n) Returns n bytes of strongly encrypted random data

3、fileinput

The fileinput module allows you to easily iterate over all lines in a series of text files.

Function/variable Description
input([files[,inplace[,backup]]]) Help iterate over rows in multiple input streams
filename() Returns the name of the current file
lineno () Return (cumulative) current line number
filelineno () Return the line number in the current file
isfirstline() Check if the current line is the first line in the file
isstdin() Check if the last line comes from sys.stdin
nextfile() Close the current file and move to the next file
close() Close sequence

4. Sets, heaps, and deques

4.1, collection

The collection is implemented by the built-in class set. This means that you can create collections directly without importing classes:

>>> set(range(10))
{
    
    0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

You can use sequences (or other iterable objects) to create collections, or you can use curly braces to explicitly specify them. Note that you cannot just use curly braces to create an empty set, as this will create a dictionary.

>>> type({
    
    })
<class 'dict'>

The collection is mainly used for membership checking, so duplicate elements will be ignored :

>>> {
    
    0,0,1,2,1,4,5,5,5,4}
{
    
    0, 1, 2, 4, 5}

Like a dictionary, the order of elements in a collection is different .

In addition to membership checks, various standard set operations can be performed, such as union and intersection:

>>> a = {
    
    1,2,3}
>>> b = {
    
    2,3,4}
>>> a.union(b)
{
    
    1, 2, 3, 4}
>>> a | b
{
    
    1, 2, 3, 4}

There are some other methods and operators:

>>> c = a & b
>>> c.issubset(a)
True
>>> c <= a
True
>>> c.issuperset(a)
False
>>> c >= a
False
>>> a.intersection(b)
{
    
    2, 3}
>>> a & b
{
    
    2, 3}
>>> a.difference(b)
{
    
    1}
>>> a - b
{
    
    1}
>>> a ^ b
{
    
    1, 4}
>>> a.copy()
{
    
    1, 2, 3}
>>> a.copy() is a
False

Sets are mutable, so they cannot be used as dictionary keys . Another problem is that collections can only contain immutable values, so they cannot contain other collections .

>>> a = set()
>>> b = set()
>>> a.add(b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'

The constructor forzenset creates a copy of the given set. Useful when you need to use a collection as a member of another collection or as a key in a dictionary.

4.2, heap

It is a priority queue that allows you to add objects in any order and find (and delete) the smallest element at any time . The module is named heapq.

Function/variable Description
heappush(heap,x) Push x into the heap
heappop(heap) Pop the smallest element from the heap
heapify(heap) Let the list have heap characteristics
heapreolace(heap,x) Pop the smallest element and push x into the heap
nlargest (n trip) Returns the n largest elements in iter
nsmallest(n,iter) Returns the n smallest elements in iter
>>> from heapq import *
>>> from random import shuffle
>>> data = list(range(10))
>>> shuffle(data)
>>> heap = []
>>> for n in data:
...     heappush(heap,n)
...
>>> heap
[0, 1, 6, 2, 4, 7, 9, 8, 3, 5]
>>> heappush(heap,0.5)
>>> heap
[0, 0.5, 6, 2, 1, 7, 9, 8, 3, 5, 4]

It is the big top heap in the data structure, that is, there is still a certain order of arrangement.

>>> heappop(heap)
0
>>> heappop(heap)
0.5
>>> heappop(heap)
1
>>> heap
[2, 3, 6, 5, 4, 7, 9, 8]
>>> heap = [5,8,0,3,6,7,9,1,4,2]
>>> heapify(heap)			#就是调整堆的过程
>>> heap
[0, 1, 5, 3, 2, 7, 9, 8, 4, 6]

4.3, deque

The deque is useful when you need to delete the elements in the order they were added .

>>> from collections import deque
>>> q = deque(range(5))
>>> q.append(5)
>>> q.appendleft(6)
>>> q
deque([6, 0, 1, 2, 3, 4, 5])
>>> q.pop()
5
>>> q.popleft()
6
>>> q.rotate(3)
>>> q
deque([2, 3, 4, 0, 1])
>>> q.rotate(-1)
>>> q
deque([3, 4, 0, 1, 2])

5、time

Time module configured to obtain a current time, an operation time and date, reading time from the string, the formatted date to a string format .

Fields in Python date tuple
index Field value
0 year
1 month 1~12
2 day 0~31
3 Time 0~23
4 Minute 0~59
5 second 0~61
6 week 0~6, where 0 represents Monday
7 Julian day 1~366
8 summer time 0, 1 or -1
Function/variable Description
asctime([tuple]) Convert time tuple to string
localtime([secs]) Convert seconds to local time date tuple
mktime(tuple) Convert time tuple to local time
sleep(secs) Sleep (do nothing) secs seconds
strptime(string[,format]) 将字符串转换为时间元组
time() 当前时间(从新纪元开始后的秒数)
>>> import time
>>> time.time()
1596703340.4325356
>>> time.asctime()
'Thu Aug  6 16:42:39 2020'

6、random

模块 random 包含生成伪随机数的函数

函数 说明
random() 返回一个 0~1(含)的随机数
getrandbits(n) 以长整数方式返回 n 个随机地二进制数
uniform(a,b) 返回一个 a~b(含)的随机实数
randrange([start],stop,[step]) 从 range(start,stop,step) 中随机地选择一个数
choice(seq) 从序列 seq 中随机地选择一个元素
shuffle(seq[,random]) 就地打乱序列 seq
sample(seq,n) 从序列 seq 中随机地选择 n 个值不同的元素

Guess you like

Origin blog.csdn.net/qq_36879493/article/details/107844159