<python3-cookbook> Chapter One: Data Structures and algorithms

Source: Internet
Author: User

the first chapter: Data structure and algorithm

Introduction: This book is advanced usage, not small white use book
Purpose: The purpose of writing is to record the process of learning the book and the Harvest

1.1 The decompression sequence is assigned to multiple variables:

problem : There is now one containing n elements of a tuple or a sequence, how to extract the value inside it and assign a value to n variables?

Solution: extract and assign values to multiple variables with a simple assignment statement. the only prerequisite is that the number of variables must be the same as the number of elements in the sequence.

1.2 Unzip an iterative object to assign values to multiple variables:

Questions: if the number of elements of an iterative object exceeds the number of variables, a ValueError. So how can you extract N elements out of this iterative object?

Solution: The asterisk expression in Python can be used to solve this problem

1.3 Keep the last n elements:

Questions: How to keep a history of only the last finite number of elements when iterating or doing something else ?

Solution:collections.deque

The Deque class can be used in any situation where you only need a simple queue data structure.

1.4 Find the largest or smallest n elements:

Questions: How to get the maximum or minimum from a set N List of elements?

Solution:The HEAPQ module has two functions: Nlargest () and nsmallest () can solve this problem perfectly.

1.5 Implement a priority queue:

Questions: How do I implement a priority-ordered queue? and on top of this queue, every pop operation always returns the highest-priority element.

Solution: A simple priority queue is implemented with the HEAPQ module:

1.6 keys in the dictionary map multiple values:

Questions: How do I Implement a dictionary (also called multidict) that corresponds to multiple values for a key ?

Solution: use the defaultdict in the collections module to construct such a dictionary. One feature of Defaultdict is that it automatically initializes the corresponding value for each key, so you just need to focus on adding the element action.

1.7 Dictionary Sort:

Questions: you want to create a dictionary and control the Order of the elements as you iterate or serialize the dictionary.

Solution: using the Ordereddict class in the collections module

1.8 operation of the dictionary:

Questions: How do I perform some computational operations (such as minimum, maximum, sort, etc.) in a data dictionary?

Solution: to perform a calculation on a dictionary value, you typically need to use the zip () function to reverse the key and value first, and then combine the max (), Min (), and sorted () methods to implement

1.9 Find the same point of the two dictionaries:

Questions: How do I find the same point in two dictionaries (like the same key, the same value, etc.)?

Solution: Perform a collection operation on the keys () or the items () method returned from the two dictionaries

1.10 Delete the same elements of the sequence and keep the order:

Questions: How do I keep the order of elements in a sequence and eliminate duplicate values?

Solution: if the values on the sequence are hashable types, it is easy to use the collection or generator to solve the problem.

1.11 named slices:

Questions: If your program contains a lot of hard-coded slices that you can't look straight in, and you want to clean up the code.

Solution: the built -in slice () function creates a slice object. Slice objects can be used wherever slices are used

1.12 Most frequently occurring elements in a sequence:

Questions: How do you find the most frequently occurring elements in a sequence?

Solution:collections. The Counter class is specifically designed for this type of problem, and it even has a useful most_common () method that gives the answer directly.

1.13 Sort a dictionary list by a keyword:

Questions: There is a list of dictionaries that you want to sort according to one or several dictionary fields.

Solution: by using the Itemgetter function of the operator module, it is very easy to sort such data structures.

1.14 Sorts only objects that are native compared are supported:

Questions: you want to sort objects of the same type, but they do not support native comparison operations.

Solution: The built -in sorted () function has a keyword parameter key that can pass in a callable object to it, which returns a value for each incoming object, which is sorted Used to sort the objects.

1.15 Group records by a field:

Questions: you have a sequence of dictionaries or instances, and then you want to iterate through a specific field such as date.

Solution:the Itertools.groupby () function is useful for such data grouping operations.

1.16 Filtering sequence elements:

Questions: you have a data series that you want to use to extract the required values from or shorten the sequence

Solution: use a list derivation to iterate over the filtered elements using a generator expression

1.17 Extracting a subset from the dictionary:

Questions: you want to construct a dictionary, which is a subset of another dictionary.

Solution: dictionary derivation, by creating a tuple sequence and then passing it to the dict () function also implements

1.18 map names to sequence elements:

Questions: you have a code that accesses a list or an element in a tuple by subscript, but sometimes it makes your code difficult to read . so you want to access the element by name.

Solution:the Collections.namedtuple () function helps you solve this problem by using an ordinary tuple object

1.19 convert and compute data simultaneously:

Questions: you need to perform aggregate functions on the data series (such as sum (), Min (), Max ()), but first you need to convert or filter the data

Solution: a very elegant way to combine data calculation and conversion is to use a generator expression parameter.

1.20 Merging multiple dictionaries and mappings:

Questions: Now that you have multiple dictionaries or mappings, you want to combine them logically into a single map to perform certain operations, such as finding values or checking for the existence of certain keys.

Solution: use the Chainmap class in the collections module. A chainmap accepts multiple dictionaries and logically changes them to a dictionary.

<python3-cookbook> Chapter One: 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.