Python Study Notes 2: Build sequence: List derivation and generator expression, python Study Notes

Source: Internet
Author: User
Tags python list

Python Study Notes 2: Build sequence: List derivation and generator expression, python Study Notes
Welcome to my website: www. comingnext. cn1. about Python built-in Sequence Types

 

A. differentiate container Sequences Based on whether different types of data can be stored:

The list, tuple, and collections. deque sequences can store different types of data.

Flat sequence:

Str, bytes, bytearray, memoryview, and array. array can only accommodate one type.

 

B. Variable Sequence classification based on whether the sequence can be modified:

List, bytearray, array. array, collections. deque, and memoryview.

Immutable sequence:

Tuple, str, and bytes.

The most important and basic Python built-in sequence is list. list is both a container sequence and a variable sequence.

 

2. Python list

 

A. List Method

The list contains many methods, which are taken from the official documentation below:

List. append (x)
Add the project to the end of the list. Equivalent to a [len (a):] = [x].

List. extend (L)
The list is extended by appending all items in the given list. Equivalent to a [len (a):] = L.

List. insert (I, x) inserts a project at a given position. The first parameter is the index of the inserted element, so. insert (0, x) in the list header,. insert (len (a), x) is equivalent to. append (x ).

List. remove (x) removes the first item with the value of x from the list. It is an error if such a project does not exist.

List. pop ([I]) deletes the project at the specified position in the list and returns it. If no position is specified, a. pop () will delete and return the last element in the list. (Square brackets around I in the method declaration indicate that the parameter is optional, instead of entering square brackets at this position. You will frequently see this symbol in the Python library reference .)

List. clear ()
Delete all projects from the list. Equivalent to del a [:].

List. index (x)
The return value is the index in the list of the first project of x. It is an error if such a project does not exist.

List. count (x)
Returns the number of times x appears in the list.

List. sort (key = None, reverse = False) items in the sorting list (parameters can be customized, see sorted ()).

List. reverse ()
The elements in the list are reversed by position.

List. copy ()
Returns the shortest copy of the list. Equivalent to a [:].

 

B. Use the sample list as a stack:
>>> x = [1,2,3,4,5]>>> x.append(6)>>> x[1, 2, 3, 4, 5, 6]>>> x.pop()6>>> x[1, 2, 3, 4, 5]

 

The list is used as a queue:
>>> From collections import deque # To implement a queue, collections. deque is designed for fast operations from both ends. >>> Queue = deque (x) >>> queuedeque ([1, 2, 3, 4, 5]) >>> queue. append (6) >>> queuedeque ([1, 2, 3, 4, 5, 6]) >>> queue. popleft () 1 >>> queue. pop () 6 >>> queuedeque ([2, 3, 4, 5])

 

 

3. List Derivation

 

A. Normal list

List derivation is a shortcut for Python to build a new list.
The simplest usage is as follows:

>>> chars = 'ABCD'>>> list = []>>> for char in chars:...     list.append(char)...>>> list['A', 'B', 'C', 'D']

 

Or this method:

>>> chars = 'ABCD'>>> list = [char for char in chars]>>> list['A', 'B', 'C', 'D']

 

For those who have learned Python, the second type is more readable, the code is concise, and the second type is more Python style. Therefore, the second method is recommended.

 

B. flute

The flute product is a list. The elements in the list are tuples composed of input iteratable element pairs. Therefore, the length of the flute product list is equal to the product of the length of the input variable. You can use list derivation to generate two or more iteratable types of cartesian products:

>>> cross = [(x,y) for x in range(4) for y in range(4)]>>> cross[(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3), (3, 0), (3, 1), (3, 2), (3, 3)]>>> colors = ['black', 'white']>>> sizes = ['S', 'M', 'L']>>> tshirts = [(color, size) for color in colors for size in sizes]>>> tshirts[('black', 'S'), ('black', 'M'), ('black', 'L'), ('white', 'S'), ('white', 'M'), ('white', 'L')]>>> tshirts = [(color,size) for size in sizes...                         for color in colors]>>> tshirts[('black', 'S'), ('white', 'S'), ('black', 'M'), ('white', 'M'), ('black', 'L'), ('white', 'L')]>>>

 

 

4. Generator expression


If you want to generate sequences of other types, the generator expression will be useful.

Although list derivation can also be used to initialize tuples, arrays, or other sequence types, the generator expression is a better choice. The biggest difference between the two is that the generator expression follows the iterator protocol and can generate elements one by one instead of creating a complete list first, then pass the list to a constructor. This method can obviously save memory.

The syntax of the generator expression is similar to that of list derivation, except that square brackets are replaced with parentheses (connected ):

>>> tshirts = ((color, size) for color in colors for size in sizes)>>> tshirts<generator object <genexpr> at 0x00000245FC9D40A0>>>> print(tshirts)>>> for tshirt in tshirts:...     print(tshirt)...('black', 'S')('black', 'M')('black', 'L')('white', 'S')('white', 'M')('white', 'L')

 

In this example, we can see that the tshirts obtained by the generator expression is a generator, and in the previous example, the list derivation generates a list. The difference is that (), the last one is [].
In this example, tshirts is a generator object that can be iterated. When tshirts is generated, a list is not left in the memory, so it is printed at 0x00000245FC9D40A0>. A combination is generated every time the for loop is run, so that the content of the table can be printed, therefore, you can print only some of the data, instead of all the data. In other words, it is used to generate content. when the data is large, the generator expression can significantly save memory.

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.