collections module
1.namedtuple (named tuple)
Generation can be accessed by name For example, the tuple of the element means x is 1 and y is 2 coordinates
Use from collections import namedtuple to import module
from collections import namedtuple # import module Go to res = namedtuple('location',['x','y','z']) # parameter two can be filled with iterable object parameter one is a name or res = namedtuple('location','xy z ') # Strings can be used but separated by spaces A = res(123,124,125) # Note that the number of elements must be the same as the namedtuple, otherwise an error will be reported print(A) >>>> Position (x=123,y=124 ,z=125)print(Ax) >>> 123print(Ay) >>> 124print(Az) >>> 125
2.queue queue
Queue: FIFO first in first out
import queue #Import module q = queue.Queue() #Generate queue object q.put('first') # Put the value in the queue q.put('second') #Continue to put the value in it print(q) >>>>To get an object address, you need to use the get method to get print(q.get ()) # Ask the queue for a value print(q.get())print(q.get()) # If the value in the queue is exhausted, the program will wait in place until the value is obtained from the queue
< h2 id="deque double-ended queue">3.deque double-ended queue
When using list to store data, although the index is very fast, deleting and inserting elements is very slow. You can use the deque module to Quick insert and delete method Add at the end append Add at the beginning appendleft Delete the end pop Delete Insert insert in the middle except popleft at the beginning
from collections import deque # Import module res = [1,2,3,4,5] #Generate a list res2 = deque(res) print( res2) >>>>> deque([1,2,3,4,5])res2.append('here is the right') res2.appendleft('here is the left')print(res2) >>>>> >deque(['Here is the left', 1, 2, 3, 4, 5,'Here is the right'])# Use the delete method to delete both the left and right sides res2.pop()res2.popleft()print(res2)> >>>>deque([1,2,3,4,5])
The queue should not support insertion at any position, only special points can be inserted end to end. The deque can be inserted at any position according to the index< /p>
res2.insert(1,'hello')print(res2) >>>>>deque[1,'hello',2,3,4,5]
4.OrderedDict
When using a dictionary, the keys are unordered. When iterating the dictionary, we cannot determine the order of the keys. If you need the keys to maintain the order, You can use OrderedDict
from collections import OrderedDicta = OrderedDict([('a',1),('b',2),('c',3)]) # Generate A dictionary with ordered keys. Note that the keys of OrderedDict will be arranged in the order of insertion, not the order of the keys themselves: >>> od = OrderedDict()>>> od['z'] = 1>>> od['y' ] = 2>>> od['x'] = 3>>> od.keys() # Return according to the order of the inserted keys ['z','y','x']
5.defaultdict
When using dict
, if the referenced Key does not exist, KeyError
will be thrown. If you want to return a default value when the key does not exist, you can use `defaultdict’# key does not exist, return to the default value
from collections import defaultdictvalues = [11, 22, 33, 44,55,66,77,88,99,90]my_dict = defaultdict(list)for value in values: if value>66: my_dict['k1'].append(value) else: my_dict['k2']. append(value)
6.Counter() uses a dictionary to show the number of each character {character :Number}
from collections import Counters ='abcdeabcdabcaba'res = Counter(s)print(res)>>>Counter({'a': 5,'b': 4,'c': 3,'d': 2,'e': 1})
Two. Time module time
1 . Three manifestations of the time module 1. Timestamp Generally speaking, the timestamp represents the offset 2 formatted in seconds starting from January 1, 1970 00:00:00 (show them) 3. Structured time
import timeprint(time.time()) # Look at the timestamp
2. Format the time
import time
print(time.strftime('%Y %m %d %H%M%S'))
print(time.strftime('%Y-%m-%d %X' )) # %X is equivalent to %H:%M:%S
3. Structured time
import timeprint(time.localtime())>>>time.struct_time(tm_year=2019, tm_mon=7, tm_mday=18, tm_hour=20, tm_min=20, tm_sec=45, tm_wday=3, tm_yday=199, tm_isdst=0 )
datetime
import datetimeprint(datetime.date.today()) # date>>>: year, month, day print(datetime. datetime.today()) # datetime>>>: year, month, day, hour, minute and second res = datetime.date.today()print(res.year)print(res.month)print(res.day)print(res.weekday( )) # 0-6 means week 0 means Monday print(res.isoweekday()) # 1-7 means week 7 is Sunday """ (******) date object = date object +/- timedelta object timedelta object = date object +/- date object """ current_time = datetime.date.today() # date object timetel_t = datetime.timedelta(days=7) # timedelta object res1 = current_time+timetel_t # date object# UTC time dt_today = datetime.datetime.today()dt_now = datetime.datetime.now()dt_utcnow = datetime.datetime.utcnow()print(dt_utcnow,dt_now,dt_today)>>>>2019-07-18 12:42:21.087353 2019- 07-18 20:42:21.087353 2019-07-18 20:42:21.087353