Python3 from zero--{Initial awareness: Data structures and Algorithms}

Source: Internet
Author: User
Tags iterable

One, efficiently insert, delete elements from both ends of the queue, and retain a fixed number of data entries:

Collections.deque ([iterable[,maxlen=n]])

A = Collections.deque ([1, 2],maxlen=3)

A.appendleft (3)

[3, 1, 2]

A.appendleft (4)

[4, 3, 1]

A.popleft ()

[3, 1]

To find the largest or smallest n elements in a queue

Ideas 1:heapq.nlargest (n, iterable, Key=none), Heapq.nsmallest (n, iterable, key=xxx)

Idea 2: First sort, then slice: sorted (items) [: N], sorted (items) [-N:]

If the object is a dictionary, it is possible to reverse the dictionary's key and value into a list containing tuples, such as: min_xxx = min (Zip (dict.values (), Dict.key ()), with zip

Iii. Implementing a custom priority queue

Heapq.heappush (heap, item), item represents a custom priority identifier, which can be a tuple, a list, etc. to implement a multi-level cascade

Heapq.heappop (heap), culling and displaying the element with the lowest combined priority

Four, the dictionary key, Key-value support common collection operations (value does not support), such as The Set (&), Intersection (|), Difference (one-way-, two-way ^), etc., without prior conversion to a collection, can be used to compare two dictionaries between the keys or items of similarities and differences, overlap, etc. such as: A.keys ()-B.keys (), A.items () & B.items ()

V. Finding the most frequently occurring elements in a sequence

First collections. Counter (LIST/TUPLE/STR) forms a Counter object and then collections. Counter.most_common (n), you can get the "top n most frequently occurring elements". In the underlying implementation, counter is a dictionary that maps between the elements and the number of occurrences of them, and the counter can be used to perform mathematical operations such as +-*/. Update append source data for updated count results; details help (collections. Counter)

VI. filtering elements in a sequence that can be replaced at the same time

List derivation, example: Test = [n**2 if n > 0 else 0 for N in MyList]

For complex filter conditions, the filter logic is first placed in a separate function and then processed using the built-in filter () function: test = list (My_def, values), showing only the My_ def (usually try-except structure) a list of value consisting of the result of true

Extracting a character set that conforms to a custom condition from a dictionary

Example: sub_dict = {Key:value for key, value in My_dict.items () if value > 200 or if key in Other_dict}

Eight, enumerate (iterable, start=0), add an index sequence for the original object, you can customize the index start number

 for  in enumerate ({'a': 1,'b': 2}.items (), start=10) :...   Print  Ten ('b', 2)One ('a', 1)

Nine, built-in functions: sorted, reversed, do not modify the source data;. Sort,. Reverse is a way to list, dictionary, and so on, to modify the source data in situ

Sorted (iterable, Key=none, Reverse=false)

X. ABS (INT/FLOAT), any (iterable), All (iterable)

ABS: Return absolute value

All (): Returns True if any element inside the iterator is not 0 or non-null, otherwise false

Any (): Returns True if one or more of the elements inside the iterator are not 0 or non-null; otherwise false

Xi. convert and compute data simultaneously: using the generator derivation ———— efficient and elegant; The generator scheme transforms the data iteratively, saving memory

#determine if any. py files exist in a directoryImportOsfiles= Os.listdir ('dirname')ifAny (Name.endswith ('. PY') forNameinchfiles):Print('there be python!')Else:    Print('Sorry, no python.')#Output a tuple as CSVs = ('ACME', 50, 123.45)Print(','. Join (STR (x) forXinchs)) #join the object being processed is a string#data reduction across fields of a data structurePortfolio = [    {'name':'GOOG','shares': 50},    {'name':'YHOO','shares': 75},    {'name':'AOL','shares': 20},    {'name':'Scox','shares': 65}]min_shares= Min (s['shares'] forSinchportfolio)#Original:returnsmin_shares = min (s['shares'] forSinchportfolio)#alternative:returns {' name ': ' AOL ', ' shares ':min_shares = min (Portfolio, key=Lambdas:s['shares']) # generates an iterator

12. Merging multiple dictionaries or mappings

Thinking 1:from collections Import Chainmap, is only logically connected to two dictionaries, does not create a new dictionary, priority query location in front of the dictionary data, the original dictionary of data changes can be reflected synchronously

A = {'x': 1,'Z': 3}b= {'y': 2,'Z': 4 } fromCollectionsImportCHAINMAPC=Chainmap (A, b)Print(c['x'])#Outputs 1 (from a)Print(c['y'])#Outputs 2 (from B)Print(c['Z'])#Outputs 3 (from a)

Idea 2:dict_bak.update ({new_dict}), update the original dictionary (copy), the original duplicate key's value will be overwritten, can only query to the new dictionary data, the original dictionary changes can not be reflected synchronously

Test = Dict (a)    #用dict生成原字典的副本 without destroying the original dictionary data
c = Test.update (b)print(c['z'# Outputs 4 (from B)

Python3 from zero--{Initial awareness: Data structures and Algorithms}

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.