Contents
1. sys
(1) sys.argv
sys.argv
: it is a list containing the command arguments
that are passed to the program, and argv[0] is the script name.
import sys
sys.argv
>>>
['D:\\applications\\anaconda\\lib\\site-packages\\ipykernel_launcher.py',
'-f',
'C:\\Users\\方欢\\AppData\\Roaming\\jupyter\\runtime\\kernel-54a57424-54c5-4c57-8eb8-2b54c0524b85.json']
sys.argv[0]
>>>
'D:\\applications\\anaconda\\lib\\site-packages\\ipykernel_launcher.py'
(2) sys.modules
The mapping sys.modules
maps module names to actual modules. It applies to only currently imported modules.
(3) sys.path
It’s a list of strings, in which each string is the name of a directory where the interpreter will look for modules when an import statement is executed.
(4) sys.platform
The module variable sys.platform (a string) is simply the name of the “platform” on which the interpreter is running.
(5) sys.stdin, sys.stdout, sys.stderr
The module variables sys.stdin, sys.stdout, and sys.stderr are file-like stream objects.
sys.stdin
>>>
<_io.TextIOWrapper name='<stdin>' mode='r' encoding='cp936'>
2. Heaps
-
Heap is a kind of priority queue. A priority queue lets you add objects in an arbitrary order and at any time find the smallest element.
-
There is a module
heapq
with heap-manipulating methods,You must use a list as the heap object itself:heappush(heap, x)
: Pushes x onto the heapheappop(heap)
: Pops off the smallest element in the heapheapify(heap)
: Enforces the heap property on an arbitrary listheapreplace(heap, x)
: Pops off the smallest element and pushesnlargest(n, iter)
: Returns the n largest elements of iternsmallest(n, iter)
:Returns the n smallest elements of 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, 4, 2, 3, 6, 8, 9, 5, 7]
heappop(heap)
>>>
0
heappop(heap)
>>>
1
heap
>>>
[2, 4, 3, 6, 8, 5, 7, 9]
- The
heapify
functiontakes an arbitrary list and makes it a legal heap (that is, it imposes the heap property) through the least possible amount of shuffling
. If you don’t build your heap from scratch with heappush, this is the function to use before starting to use heappush and heappop.
3. Deques
The deque
type, along with several other collection types, is found in the collections
module.
from collections import deque
q=deque(range(5)) # construct deque
q
>>>
deque([0, 1, 2, 3, 4]) #a deque object
q.appendleft(5)
q
>>>
deque([5, 0, 1, 2, 3, 4])
q.append(6)
q
>>>
deque([5, 0, 1, 2, 3, 4, 6])
q.pop()
>>>
6
q
>>>
deque([5, 0, 1, 2, 3,4])
q.popleft()
>>>
5
q
>>>
deque([0, 1, 2, 3, 4])
q.rotate(3)
>>>
deque([2, 3, 4, 0, 1])
q.rotate(-1)
>>>
deque([3, 4, 0, 1, 2])