Python Cookbook-1-Data structures and algorithms

Source: Internet
Author: User

1 Sequence decompression: through * to pass the match

*a, B = somelist, First, *mid, last = Somelist, a, *b = Somelist

2 using bidirectional queues: From collections import deque

Q = deque (maxlen=5) can be fixed length

Q = deque () can also be any length

can be inserted and removed from both ends, append, Appendleft, pop, popleft

3 finding the largest or smallest n elements: using heapq (heap queue)

HEAPQ. nlargest (N, Alist) heapq. nsmallest (n, alist) is suitable when n is relatively small

You can also sorted (alist) [-N:] Sorted (alist) [: n] for relatively large n

4 Implementing a priority queue

Import HEAPQ class priorityqueue:     def __init__ (self):         = []        = 0    def  push (self, item, priority):        Heapq.heappush (self._ Queue, (-priority, Self._index, item        )+ = 1    def  pop (self):         return Heapq.heappop (self._queue) [-1]

5 keys in a field map multiple values Defaultdict

Defaultdict
Defaultdict(list)d[' a '].  Append(1)d[' a '].  Append(2)
d[' B '].append (5)

Python Cookbook-1-data structures and algorithms

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.