Python data structure (ii)

Source: Internet
Author: User
Tags for in range

Array fixed type data series, similar to list, except that members must be of the same base type

array.typecodes #包含所有可用类型代码的字符串bBuhHiIlLqQfd

Input Code Type C python type minimum number of bytes Notes
‘b‘ Signature characters Int 1
‘B‘ unsigned characters Int 1
‘u‘ Py_unicode Unicode characters 2 (1)
‘h‘ Sign Short Int 2
‘H‘ unsigned short Int 2
‘i‘ Signature int Int 2
‘I‘ unsigned integer Int 2
‘l‘ Long signature Int 4
‘L‘ unsigned long integers Int 4
‘q‘ Signed for a long time. Int 8 (2)
‘Q‘ unsigned long long Int 8 (2)
‘f‘ Floating Floating 4
‘d‘ Double Floating 8

ImportArrayImportBinasciis='This is a ARRAY'W= [1,2,3,4]a= Array.array ('u', s)#you need to pass a parameter when instantiatingb = Array.array ('I', W)Print(A,binascii.hexlify (a), b,binascii.hexlify (b)) results: Array ('u','This is a ARRAY') b'740068006900730020006900730020006100200041005200520041005900'Array'I', [1, 2, 3, 4]) b'01000000020000000300000004000000'
#working with arrays, similar to other Python sequences, can be extended and processed in the same way as arrayA = Array.array ('I', Range (3))Print(a) A.extend (range (3))Print(A,a[3:5],list (Enumerate (a))) Results: Array ('I', [0, 1, 2]) Array ('I', [0, 1, 2, 0, 1, 2]) array ('I', [0, 1]) [(0, 0), (1, 1), (2, 2), (3, 0), (4, 1), (5, 2)]

HEAPQ heap sorting algorithm, heap is a tree data structure, where child nodes and parent nodes are an ordered relationship.

#Create HeapImportHeapqheap1= [] forIinch[19,9,4,10,11]:#elements are inserted one by one, forming a heap structureHeapq.heappush (heap1,i)Print(HEAP1) heap2= [19,9,4,10,11]#target already exists, direct conversion heap structureheapq.heapify (HEAP2)Print(HEAP2) forIinch[0,13]: Heapq.heapreplace (heap2,i)#maintain a fixed-size heap, deleting one element at a time and removing the smallest elementPrint(HEAP2)#Heappop () to delete the minimum value element forIinchRange (len (HEAP1)):Print(Heapq.heappop (HEAP1), end=',')Print()
Results: [4, 10, 9, 19, 11][4, 9, 19, 10, 11][9, 10, 19, 13, 11]4,9,10,11,19,

Bisect array two divide algorithm that supports maintaining lists in sorted order without having to sort the list after each insert. For the long list of expensive comparison operations, this may be a more common method of improvement. The module is called bisect because it uses the basic binary algorithm to complete its work,

Import bisect Import Random
= [] for in range (1,10): = random.randint (1,100) = Bisect.bisect (l,r) bisect.insort (l,r) print('%3d%3d' %

18 0 [18]
73 1 [18, 73]
98 2 [18, 73, 98]
9 0 [9, 18, 73, 98]
33 2 [9, 18, 33, 73, 98]
16 1 [9, 16, 18, 33, 73, 98]
64 4 [9, 16, 18, 33, 64, 73, 98]
98 7 [9, 16, 18, 33, 64, 73, 98, 98]
58 4 [9, 16, 18, 33, 58, 64, 73, 98, 98]

Handling Duplicates:

bisect.bisect_left( a , x , lo = 0 , hi = Len (a) )

bisect. bisect_right ( a , x , lo = 0 , hi = Len (a) )

bisect . insort_left ( a , x , lo = 0 , hi = Len (a) )

bisect.insort_right( a , x , lo = 0 , hi = Len (a) )

ImportbisectImportRandomrandom.seed (1) L= [] forIinchRange (1,10): R= Random.randint (1,100) Position=bisect.bisect_left (l,r) bisect.insort (l,r)Print('%3d%3d'%(r,position), L) Results:18 0 [18] 73 1 [18, 73] 98 2 [18, 73, 98]  9 0 [9, 18, 73, 98] 33 2 [9, 18, 33, 73, 98] 16 1 [9, 16, 18, 33, 73, 98] 64 4 [9, 16, 18, 33, 64, 73, 98] 98 6 [9, 16, 18, 33, 64, 73, 98, 98]#The same value is on the left.58 4 [9, 16, 18, 33, 58, 64, 73, 98, 98]

The Queue module provides an advanced first-out FIFO data structure for use with multithreaded programming that can be used to securely pass messages or data between producers and consumer threads, handle locks for callers, and enable multiple threads to handle the same queue instance safely

#the basic FIFOImportQueueq=queue. Queue () forIinchRange (5): Q.put (i)#element Additions while  notq.empty ():Print(Q.get ())#element DeletionResults 01234#LIFO queue, Lifoqueue uses a last in, first out (LIFO) order, usually associated with a stack structureImportQueueq=queue. Lifoqueue () forIinchRange (5): Q.put (i)#element Additions while  notq.empty ():Print(Q.get ())#element DeletionResults:43210#priority queue, Priorityqueue uses the ordered order of the contents of the queue to determine which element to getImportQueueImportThreadingclassJob ():def __init__(self,priority,description): Self.priority=Priority Self.description=DescriptionPrint('New Job', description)def __lt__(self, Other):returnSelf.priority <Other.priorityq=queue. Priorityqueue () q.put (Job (3,'Mid-level Job')) Q.put (Job (10,'Low-level Job')) Q.put (Job (1,'Important-level Job'))defprocess_job (q): whileTrue:next_job=Q.get ()Print('Processing job:', Next_job.description) q.task_done ()#use Task_done () to indicate that the item has been retrieved and that all work is completed and the count is reducedWorkers= [Threading. Thread (target=process_job,args=(q,)), threading. Thread (Target=process_job,args=(q,)),] forWinchWorkers:Print(W.getname ()) W.setdaemon (True) W.start () Q.join ()#block until all items in the queue are fetched and processedResult: New job mid-Level jobnew Job Low-Level Jobnew Job Important-Level Jobthread-1processing Job:important-Level Jobthread-2processing Job:mid-Level jobprocessing Job:low-level Job

struct binary data structure that interprets bytes as binary, converting between strings and binary data

Non-permanent references to WEAKREF objects

Python data structure (ii)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.