PYTHON3 Data structure

Source: Internet
Author: User
Tags pear shallow copy

Tag: The GPO function returns reverse tuples letters get end strip representation

List

The list in Python is mutable, which is the most important feature that distinguishes it from strings and tuples, in a nutshell: Lists can be modified, and strings and tuples cannot.

Here's how to list in Python:

Method Description
List.append (x) Adds an element to the end of the list, equivalent to A[len (a):] = [x].
List.extend (L) Expands the list by adding all the elements of the specified list, equivalent to A[len (a):] = L.
List.insert (i, X) Inserts an element at the specified location. The first parameter is the index of the element that is ready to be inserted before it, such as A.insert (0, X) is inserted before the entire list, while A.insert (Len (a), x) is equivalent to A.append (x).
List.remove (x) Removes the first element in the list that has a value of x. If there are no such elements, an error is returned.
List.pop ([i]) Removes the element from the specified position in the list and returns it. If no index is specified, A.pop () returns the last element. The element is removed from the list. (The square brackets on both sides of the method indicate that this parameter is optional, rather than asking you to enter a pair of parentheses, you will often encounter such tags in the Python Library Reference Manual.) )
List.clear () Remove all items in the list equal to Del a[:].
List.index (x) Returns the index of the first element in the list that has a value of x. If there are no matching elements, an error is returned.
List.count (x) Returns the number of times that X appears in the list.
List.sort () Sorts the elements in the list.
List.reverse () The elements in the table are inverted.
List.copy () Returns a shallow copy of the list, equal to a[:].

The following example shows most of the methods of a list:

>>> a = [66.25, 333, 333, 1, 1234.5]>>> print (A.count (333), A.count (66.25), A.count (' X ')) 2 1 0>>&G T A.insert (2,-1) >>> a.append (333) >>> a[66.25, 333,-1, 333, 1, 1234.5, 333]>>> a.index (333) 1& Gt;>> A.remove (333) >>> a[66.25,-1, 333, 1, 1234.5, 333]>>> a.reverse () >>> a[333, 1234.5, 1, 333,-1, 66.25]>>> a.sort () >>> a[-1, 1, 66.25, 333, 333, 1234.5]

Note: Methods such as insert, remove, or sort modify the list without returning a value.

Use a list as a stack

The list method makes it easy for a list to be used as a stack, a stack as a specific data structure, and the last element to be released (LIFO). Use the Append () method to add an element to the top of the stack. A pop () method that does not specify an index can release an element from the top of the stack. For example:

>>> stack = [3, 4, 5]>>> stack.append (6) >>> Stack.append (7) >>> stack[3, 4, 5, 6, 7]> ;>> Stack.pop () 7>>> stack[3, 4, 5, 6]>>> stack.pop () 6>>> stack.pop () 5>>> Stack[3, 4]
Use a list as a queue

You can also use the list as a queue, only the first element in the queue, the first to take out, but it is inefficient to use the list as such. Adding or ejecting elements at the end of the list is fast, but it is not easy to insert or eject from the head at the table (because all other elements move one by one).

>>> from collections import deque>>> queue = Deque (["Eric", "John", "Michael"]) >>> Queue.append ("Terry")           # Terry Arrives>>> queue.append ("Graham")          # Graham Arrives>>> Queue.popleft () # The first to                 arrive now leaves ' Eric ' >>> queue.popleft ()                 # The second-arrive now Leav Es ' John ' >>> queue                           # Remaining queue in order of Arrivaldeque ([' Michael ', ' Terry ', ' Graham '])
List-derived

The list derivation provides a simple way to create a list from a sequence. Typically, an application applies some actions to each element of a sequence, using the resulting results as an element to generate a new list, or by creating a subsequence based on a determined criterion.

Each list deduction is followed by an expression after for, and then has 0 to multiple for or if clauses. The return result is a list that is generated from the for and if contexts that are followed by the expression. If you want the expression to derive a tuple, you must use parentheses.

Here we multiply each value in the list by three to get a new list:

>>> VEC = [2, 4, 6]>>> [3*x for X in Vec][6, 12, 18]

Now let's play a little bit of tricks:

>>> [[x, X**2] for x in Vec][[2, 4], [4, 16], [6, 36]]

Here we call a method one by one for each element in a sequence:

>>> freshfruit = ['  banana ', '  loganberry ', ' passion fruit  ']>>> [Weapon.strip () for Weapon in freshfruit][' banana ', ' loganberry ', ' passion fruit ']

We can use the IF clause as a filter:

Here are a few demos of loops and other tricks:

>>> VEC1 = [2, 4, 6]>>> vec2 = [4, 3, -9]>>> [x*y for X ' vec1 for y in Vec2][8, 6,-18, 16, 1 2, -36, Max, -54]>>> [x+y for x in vec1 for y in Vec2][6, 5,-7, 8, 7, -5, ten, 9, -3]>>> [Vec1[i]*vec 2[i] for I in range (len (VEC1))][8, 12,-54]

A list derivation can use complex expressions or nested functions:

>>> [Str (Round (355/113, i)) for I in range (1, 6) [' 3.1 ', ' 3.14 ', ' 3.142 ', ' 3.1416 ', ' 3.14159 ']
Nested list parsing

The list of Python can also be nested.

The following example shows a list of matrices for 3x4:

>>> matrix = [...     [1, 2, 3, 4],...     [5, 6, 7, 8],...     [9, ten, one, one],...]

The following instance converts the matrix list of 3x4 to the 4x3 list:

>>> [[Row[i] for row and matrix] for I in range (4)][[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]

The following examples can also be implemented using the following methods:

>>> transposed = []>>> for I in range (4): ...     Transposed.append ([row[i] for row in matrix]) ...>>> transposed[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

Another way to achieve this:

>>> transposed = []>>> for I in range (4): ...     # The following 3 lines implement the nested Listcomp ...     Transposed_row = [] ...     For row in matrix: ...         Transposed_row.append (Row[i])     ... Transposed.append (Transposed_row) ...>>> transposed[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Del statement

Use the DEL statement to remove an element from a list by index rather than by value. This differs from using pop () to return a value. You can use the DEL statement to remove a cut from the list, or to clear the entire list (the method we described earlier is to assign an empty list to the cut). For example:

>>> a = [-1, 1, 66.25, 333, 333, 1234.5]>>> del a[0]>>> a[1, 66.25, 333, 333, 1234.5]>>&G T Del a[2:4]>>> a[1, 66.25, 1234.5]>>> del a[:]>>> a[]

You can also delete an entity variable with del:

>>> del A
Tuples and sequences

Tuples are made up of several comma-separated values, such as:

>>> t = 12345, 54321, ' hello! ' >>> t[0]12345>>> t (12345, 54321, ' hello! ') >>> # tuples May nested: ... u = t, (1, 2, 3, 4, 5) >>> U ((12345, 54321, ' hello! '), (1, 2, 3, 4, 5))

As you can see, tuples always have parentheses in the output so that the nested structure is correctly expressed. You may have or have no parentheses at the input, but parentheses are usually required (if the tuple is part of a larger expression).

Collection

A collection is a set of unordered, non-repeating elements. Basic features include relationship testing and elimination of duplicate elements.

You can create a collection with curly braces ({}). Note: If you want to create an empty collection, you must use Set () instead of {}; the latter creates an empty dictionary, and the next section introduces this data structure.

Here's a simple demo:

>>> basket = {' Apple ', ' orange ', ' apple ', ' pear ', ' orange ', ' banana '}>>> print (basket)                 # show that duplicates has been removed{' orange ', ' banana ', ' pear ', ' apple '}>>> ' orange ' in basket # Fast Membership testingtrue>>> ' Crabgrass ' in basketfalse>>> # demonstrate set operations on UN                                  Ique Letters from Words...>>> a = set (' Abracadabra ') >>> B = Set (' Alacazam ') >>> a # Unique letters in a{' a ', ' R ', ' B ', ' C ', ' d '}>>> A-B # let Ters in A and not in b{' R ', ' d ', ' B '}>>> a |                              B # Letters in either A or b{' a ', ' C ', ' R ', ' d ', ' B ', ' m ', ' Z ', ' l '}>>> A & B  # Letters in both A and b{' a ', ' C '}>>> a ^ B # letters in A or B but not both{' R ', ' d ', ' B ', ' m ', ' Z ', ' l '}>>> basket = {' Apple ', ' orange ',' Apple ', ' pear ', ' orange ', ' banana '}>>> print (basket) # show that duplicates has been Remov ed{' orange ', ' banana ', ' pear ', ' apple '}>>> ' orange ' in Basket # Fast Membership TESTINGTRUE>&G  T;> ' Crabgrass ' in basketfalse>>> # demonstrate set operations on unique letters from-to-words...>>>  A = set (' Abracadabra ') >>> B = Set (' Alacazam ') >>> a # unique letters in A{' A ', ' R ', ' B ', ' C ', ' d '}>>> A-B # letters in A and not in b{' R ', ' d ', ' a '}>& Gt;> A |                              B # Letters in either A or b{' a ', ' C ', ' R ', ' d ', ' B ', ' m ', ' Z ', ' l '}>>> A & B  # Letters in both A and b{' a ', ' C '}>>> a ^ B # letters in A or B but not both{' R ', ' d ', ' B ', ' m ', ' Z ', ' l '}

The collection also supports the derivation formula:

>>> a = {x for x in ' Abracadabra ' If x isn't in ' abc '}>>> a{' R ', ' d '}
Dictionary

Another very useful Python built-in data type is a dictionary.

The sequence is indexed by successive integers, and unlike this, the dictionary is indexed by keywords, which can be any immutable type, usually with a string or numeric value.

The best way to understand a dictionary is to think of it as a set of unordered key = value pairs. Within the same dictionary, the keywords must be different.

A pair of curly braces creates an empty dictionary: {}.

This is a simple example of a dictionary application:

>>> Tel = {' Jack ': 4098, ' Sape ': 4139}>>> tel[' guido '] = 4127>>> tel{' sape ': 4139, ' Guido ': 412 7, ' Jack ': 4098}>>> tel[' Jack ']4098>>> del tel[' Sape ']>>> tel[' irv '] = 4127>>> tel{ ' Guido ': 4127, ' Irv ': 4127, ' Jack ': 4098}>>> list (Tel.keys ()) [' Irv ', ' Guido ', ' Jack ']>>> sorted ( Tel.keys ()) [' Guido ', ' Irv ', ' Jack ']>>> ' Guido ' in teltrue>>> ' Jack ' not in Telfalse

The constructor Dict () constructs a dictionary directly from a key-value pair of tuples. If there is a fixed pattern, the list derivation specifies a specific key-value pair:

>>> dict ([' Sape ', 4139), (' Guido ', 4127), (' Jack ', 4098)]) {' Sape ': 4139, ' Jack ': 4098, ' Guido ': 4127}

In addition, the dictionary derivation can be used to create an expression dictionary of any key and value:

>>> {x:x**2 for x in (2, 4, 6)}{2:4, 4:16, 6:36}

If the keyword is simply a string, it is sometimes more convenient to specify the key value pair using the keyword parameter:

>>> dict (sape=4139, guido=4127, jack=4098) {' Sape ': 4139, ' Jack ': 4098, ' Guido ': 4127}
Traversal tips

When traversing in a dictionary, the keywords and corresponding values can be interpreted at the same time using the items () method:

>>> Knights = {' Gallahad ': ' The Pure ', ' Robin ': ' The Brave '}>>> for K, V in Knights.items ():     ... Print (k, v) ... Gallahad the Purerobin the Brave

When traversing a sequence, the index position and corresponding value can be obtained using the enumerate () function at the same time:

>>> for I, V in enumerate ([' Tic ', ' tac ', ' toe ']):     ... Print (i, v) ... 0 Tic1 Tac2 Toe

To traverse two or more sequences at the same time, you can use the zip () combination:

>>> questions = [' name ', ' Quest ', ' Favorite color ']>>> answers = [' Lancelot ', ' The Holy Grail ', ' Blue ']& Gt;>> for Q, A in zip (questions, answers): ...     Print (' What's your {0}?  It is {1}. '. Format (q, a)) ... What is your name?  It is Lancelot. What is your quest?  It is the Holy Grail. What is your favorite color?  It is blue.

To traverse a sequence in reverse, specify the sequence first, and then call the REVERSESD () function:

>>> for I in Reversed (range (1, ten, 2)): ...     Print (i) ... 97531

To traverse a sequence sequentially, use the sorted () function to return a sorted sequence without modifying the original value:

>>> basket = [' apple ', ' orange ', ' apple ', ' pear ', ' orange ', ' banana ']>>> for F in sorted (set (basket)): ... .     Print (f) ... applebananaorangepear

PYTHON3 Data structure

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.