Python built-in data structures

Source: Internet
Author: User
Tags for in range shallow copy

List of detailed lists

Here is a checklist of the list object methods:

list. Append (x )

adds an element to the end of the list. equivalent to A[len (a):] = [x].

list. Extend (L )

attaches all the elements in the given list L to the end of the original list A. equivalent to A[len (a):] = L.

list. Insert (i, x )

inserts an element at a given position. The first argument is the index of the element that is ready to be inserted before it, so a.insert (0, x) is inserted at the very front of the list,A.insert (Len (a), x) equivalent to a.append (x).

list. Remove (x )

removes the first element in the list that has a value of x. If there is no such element will be an error.

list. Pop ( [i])

removes the element from the given position in the list and returns it. If no index is specified,a.pop () deletes and returns the last element in the list. (the square brackets on both sides indicate that this parameter is optional, not for you to enter square brackets.) You will often see this notation in the Python Reference library).

list. Clear ( )

deletes all the elements in the list. equivalent to del a[:].

list. Index (x )

returns the index of the first element in the list that has a value of x. If there is no such element will be an error.

list. Count (x )

Returns the number of occurrences of x in the list.

list. Sort (cmp=none, Key=none, Reverse=false )

Sorts the elements in the list in place.

list. Reverse ( )

Reverses the elements in the list in situ.

list. Copy ( )

returns a shallow copy of the list, equivalent to a[:], note is "Shallow copy".

use a list as a queue

use the list as a queue, at which point the first entry is taken out (FIFO, first-out). However, the list is inefficient for this purpose because it is very fast to add and eject elements at the end of the list, but it is slow to insert or eject elements at the beginning of the list (because all other elements must be moved backwards, a common problem in the sequential container).

If you want to implement a queue, you can use Collections.deque, which is designed to quickly add and eject elements at both ends. For example:

1>>> fromCollectionsImportdeque2>>> queue = Deque (["Eric","John","Michael"])3>>> Queue.append ("Terry")#Add a try4>>> Queue.append ("Graham")#Add one more5>>> Queue.popleft ()#Delete Team Header6 'Eric'7>>> Queue.popleft ()#then delete the team head .8 'John'9>>> queue#See how many left (the last 3)TenDeque (['Michael','Terry','Graham'])

List Parsing

List parsing provides a neat way to generate a list. An application typically generates a new list from the action result of each element of a sequence, or produces a subsequence of an element that satisfies a particular condition.

For example, suppose we want to create a list of S:

1 s=[]2 for in range:3     s.append (x**2)  4print(x)5printed(s)6 ---Below is the printing--- 7 98 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Note that the variable named x that is created (or rewritten) in this for loop still exists after the loop is completed. Using the following method, we can calculate the value of s without having any side effects:

s = List (map (Lambda x:x**2, Range (10)))

Or:

 for  in range (10)]

The list parsing is enclosed in parentheses [], which contains an expression followed by a For statement followed by 0 or more for or if statements. The result is a new list consisting of the result of the expression being computed from the context of the for and if clause behind it. For example, the following Listcomp combines two elements in a list that are not equal:

1 >>> [(x, Y) for in for in    [3,1,4]    if x! = y ]2 [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

This is equivalent to the following code:

 1  >>> Combs = []  2  >>> for  x in  [1,2,3< Span style= "color: #000000;"     >]:  3  ... for  y in  [3,1,4          4  ... if  x!= y:  5   ... combs.append ((x, y)  6   ...  7  >>> Combs  8  [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] 

For a more advanced application, consider the following 3x4 matrix consisting of three 4-length lists:

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

The following list resolution allows you to transpose the matrix:

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

It is parsed from the outermost layer, that is, the function of the above code is equivalent to the following code:

1 >>> transposed = []2 for in range (4):3 ... For in       matrix]) 4 ... 5 >>> transposed6 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

  There is a way to delete an element by index from the list: the del statement. This differs from the pop () method, which has a return value. the del statement can also be used to remove slices from a list or to clear the entire list (we assign an empty list to a slice). For example:

1>>> a = [-1, 1, 66.25, 333, 333, 1234.5]2>>>delA[0]3>>>a4[1, 66.25, 333, 333, 1234.5]5>>>delA[2:4]6>>>a7[1, 66.25, 1234.5]8>>>dela[:]9>>>aTen[]

As you can see, the DEL statement actually operates directly on the list object, and functions like sorted directly return a copy of the object, so it does not change to the original list.

Python built-in data structures

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.