Python Learning Note 2: Constructing sequences: List derivation and generator expressions

Source: Internet
Author: User
Tags shallow copy

Welcome to personal website: www.comingnext.cn1. About Python built-in sequence types

A. Differentiate the container sequence by the ability to store different types of data:

list, tuple, and collections.deque these sequences can hold different types of data

Flat sequence:

STR, Bytes, ByteArray, Memoryview, and array.array, such sequences can only hold one type.

B. Classify variable sequences according to whether they 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 the list, which is both a container sequence and a mutable sequence.

2. List of Python

A. Methods of the list

The list has a number of methods, which are taken from the official documentation:

List.append (x)
Adds an item to the end of the list. Equivalent to A[len (a):] = [x].

List.extend (L)
Expands the list by attaching all items in the given list. Equivalent to A[len (a):] = L.

List.insert (i, X) inserts the item at the given location. The first parameter is the position index of the inserted element, so A.insert (0, X) inserts a value in the header of the list, A.insert (Len (a), x) equals A.append (x).

List.remove (x) removes the first item with a value of x from the list. If no such item is an error.

List.pop ([i]) deletes the item at the given position in the list and returns. If there is no given position, A.pop () will delete and return the last element in the list. (The square brackets around I in the method declaration indicate that the parameter is optional, not where you should type the square brackets.) You will see this symbol frequently in the Python library Reference. )

List.clear ()
Removes all items from the list. Equivalent to Del a[:].

List.index (x)
Returns the index of the first item in the list with a value of x. If no such item is an error.

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

List.sort (Key=none, Reverse=false) the items in the list (parameters can be customized, see sorted ()).

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

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

B. Usage example list is used 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 Import # to implement a queue, Collections.deque is designed to operate quickly 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-derived

A. General List

List derivation is a shortcut to Python to build a new list.
One of the simplest uses:

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

Or is this the method:

' ABCD '  for inch Chars] >>> list['A'B'C  ['D']

For people who have learned python, the second is more readable, and the code is more concise, while the second is more Python-style. So the second way of writing is more recommended.

B. Cartesian product

A Cartesian product is a list of elements that are composed of elements of an input iteration type, so the length of the Cartesian product list is equal to the product of the length of the input variable. A list derivation allows you to generate two or more types of Cartesian product of an iterative type:

>>> cross = [(x, Y) forXinchRange (4) forYinchRange (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) forColorinchColors forSizeinchSizes]>>>tshirts[('Black','S'), ('Black','M'), ('Black','L'), (' White','S'), (' White','M'), (' White','L')]>>> tshirts = [(color,size) forSizeinchSizes ... forColorinchColors]>>>tshirts[('Black','S'), (' White','S'), ('Black','M'), (' White','M'), ('Black','L'), (' White','L')]>>>

4. Generator expressions


Builder expressions are useful if you want to generate other types of sequences.

Although you can also use list inference to initialize tuples, arrays, or other sequence types, a builder expression is a better choice. The biggest difference between the two is that the iterator protocol is followed by the generator expression, and the elements can be produced on a single basis instead of creating a complete list before passing the list to a constructor. This is obviously a way to save memory.

The syntax of the generator expression is similar to the list deduction, except that the brackets are replaced by parentheses (then the above):

>>> tshirts = ((color, size) forColorinchColors forSizeinchsizes)>>>Tshirts<generator Object <genexpr> at 0x00000245fc9d40a0>>>>Print(tshirts)>>> forTshirtinchtshirts: ...Print(tshirt) ... ('Black','S')('Black','M')('Black','L')(' White','S')(' White','M')(' White','L')

As you can see from this example, the tshirts generated by the generator expression is a generator, and in the previous example, the list derivation generates a list, the difference is only here (), and the previous one is [].
In this case, Tshirts is a generator object that can iterate. When the tshirts is generated, it does not leave a list in memory, so it prints at 0x00000245fc9d40a0>, and a combination is generated each time the for loop runs, so that its contents can be printed. So you can also choose to print out only some of these data without having to hit them all. In other words, it is used when the content is generated, when the data is relatively large, the generator expression can significantly save memory.

Python Learning Note 2: Constructing sequences: List derivation and generator expressions

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.