Document directory
- 5.1.1 list used as stack
- 5.1.2 The list is used as a queue
- 5.1.3 list Comprehension
- 5.1.4 nested list
This chapter will describe in more detail what you have learned and add new content.
5.1 more information
There are more methods for listing data types. Below are all the methods for listing objects:
List. append (x), adding an item at the end of the list is equivalent to a [Len (a):] = [X].
List. Extend (l): expands the list by appending all the items in the given list, which is equivalent to a [Len (a):] = L.
List. insert (I, x), insert an item at the specified position. The first parameter is the index of the element to be inserted before it, so. insert (0, x) is inserted at the front end of the list, and. insert (LEN (A), X) is equivalent to. append (X ).
List. Remove (X) to remove the first item in the list with the value of X. If this item does not exist in the list, an error is returned.
List. Pop ([I]), remove the item at the specified position in the list, and return it. If no index is specified, A. Pop () is removed and the last item in the list is returned. (In the method signature, I is surrounded by square brackets, indicating that the parameter is optional. It is not the place where you should enter square brackets .)
List. Index (x) returns the index of the first item in the list with the value of X. If this item does not exist in the list, an error is returned.
List. Count (x), returns the number of times X appears in the list.
List. Sort (), sort all items in the list by position.
List. Reverse (). All items in the list are reversed by position.
An example uses most of the list methods:
You may have noticed that the methods for modifying the list like insert, remove, or sort are not printed out, and they return none. This is a design principle for all modifiable data structures in Python.
5.1.1 list used as stack
The list method can easily use the list as a stack. The last element is obtained from the first element (first, and foremost ). Add an item at the top of the stack and use the append () method. Obtain an item at the top of the stack. Use the POP () method without specifying parameters. For example:
5.1.2 The list is used as a queue
You can also use the list as a queue. The first element is the place obtained by the first element (first-in-first-out). This list is not very effective for this purpose. Append and pop-up from the end of the list are very fast. It is very slow to insert and pop-up at the beginning of the List (because all other elements need to move one position ).
Implement a queue and use collections. deque. It is designed to append and pop up from both ends very quickly. For example:
5.1.3 list Comprehension
List comprehension provides a simple way to create a list. A common application creates a new list. each of its elements is the result of some operations applied to each member of another sequence or iteratable object, or create a subsequence of those elements that meet a definite condition.
For example, suppose we want to create a list of squares, such:
We can get the same result:
This is also equivalent to squares = List (MAP (lambda X: X ** 2, range (10), but more concise and readable.
A list consists of an expression that contains the for clause followed by a for clause, followed by square brackets of zero or more for or if clauses. The result is a new list. It is calculated from the context of the for or if clause after the expression. For example, this listcomp will connect two list elements if they are not equal:
It is equivalent:
Note how the order of the for and if statements is the same in these code snippets.
If the expression is a tuples (for example, in the previous example (x, y), it must be enclosed:
A list can contain complex expressions and nested functions:
5.1.4 nested list
The initialization expression in a list comprehension can be any expression, including the understanding of another list.
Consider the following example of the 3x4 matrix as a list of three elements with a length of 4:
The following list will transpose all rows and columns:
As we can see in the previous section, the nested listcomp is calculated in the context of the for statement after it, so this example is equivalent:
In order, as shown below:
In the real world, you should first choose built-in functions instead of complex statement streams. For this usage, the zip () function will do most of the work:
5.2 del statement
One way is to remove a del statement from the list using the element index instead of the element value. This is different from the POP () method with return values. The Del statement can also be used to remove a slice from the list or clear the entire list (earlier, we used to assign an empty list to a slice ). For example:
Del can also be used to delete the entire variable:
If you reference name a later, an error will be reported (at least until another value is assigned to it ). We will find other del usage later.
5.3 tuples and Sequences
We can see that the list and string have many common attributes, such as index and slice operations. They are two examples of the series data type. Because python is an evolving language, other sequence data types can also be added. There is also another standard sequence data type: tuples.
A tuple consists of comma-separated values, for example:
As you can see, the output tuples are always enclosed in parentheses, so the nested tuples can be correctly interpreted; the input can be enclosed by or without parentheses, although parentheses are usually required (if the tuples are part of a large expression ). It is impossible to assign values to individual items of a single tuples. However, you can create a tuples containing variable objects, just like a list.
Although tuples look like lists, they are usually used for different situations and purposes. Tuples are unchangeable. elements that contain a complex sequence are usually accessed through decompression or indexing. The list can be changed. Its elements are usually similar and accessed through iteration on the list.
A special problem is the creation of tuples that contain zero or one item: The syntax is somewhat odd to adapt to it. Empty tuples are composed of an empty pair of parentheses. One entry's tuples consist of values with commas (,). It is not enough to enclose a single value with parentheses ). It looks ugly but effective. For example:
Statement t = 12345,543 21, 'Hello! 'Is an example of tuples compressed; values 12345, 54321, and 'Hello! 'Is compressed to a single tuples. The opposite operation is also possible:
This is called sequence decompression, Which is suitable enough for the sequence on the right. Sequence decompression requires that the number of variables on the left of the equal sign is equal to the number of sequence elements on the right. Note that multivariate assignment is the combination of triple compression and sequence decompression.
5.4 set
Python also contains collection data types. A set is an unordered, non-repeating dataset. Basic applications include testing member relationships and removing duplicate entities. The Set object also supports mathematical operations, such as Union, intersection, difference set, and symmetric difference set.
Curly braces or the Set () function can be used to create a set. Note that you must use set () instead of {} to create an empty set {}. The latter is used to create an empty dictionary. We will discuss this data structure in the next section.
This is a simple demonstration:
Similar to a list, a set can be understood as follows:
5.5 dictionary
Another useful data type built in python is dictionary. In other languages, dictionaries are usually called associated storage or associated arrays. Unlike a sequence, it is indexed by a series of numbers. The dictionary is indexed by key value, which can be any unchangeable type. Both strings and numbers can be used as keys. Tuples can also be used as keys if they only contain strings, numbers, or tuples. If a tuple directly or indirectly contains a mutable object, it cannot be used as a key. You cannot use the list as the key, because the list can use the index to assign values by position, slice to assign values, or the append () and extend () methods.
It is best to think of the dictionary as an unordered set of key-value pairs. All keys in a dictionary must be unique. Create an empty dictionary with a pair of curly brackets. Put a comma-separated key-Value Pair list to initialize this dictionary, which is the dictionary output method.
The main operation of the dictionary is to use keys to store or obtain values. You can also use the del expression to delete key-value pairs. If you use an existing key for storage, the old value associated with the key will be overwritten. If you use a key that does not exist to obtain the value, an error occurs.
Execute list (D. Keys () on a dictionary to return a list Of all keys in any order (if you want to sort them, use sorted (D. Keys ())). Check whether a key is in the dictionary and use the in keyword.
This is a small example of dictionary usage:
Dict () constructor builds a dictionary directly from the key-value pairs of the sequence:
In addition, you can use any key-value expression to create a dictionary:
When a key is a simple string, it is easier to use a keyword parameter to specify a key-Value Pair:
5.6 Recycling Technology
When looping the dictionary, you can use the items () method to obtain both the key and the corresponding value:
When the cyclic sequence is used, you can use the enumerate () function to obtain both the location index and the corresponding value:
When repeating two or more sequences at the same time, you can use the ZIP () function to pair items:
When repeating a sequence in reverse order, first specify the sequence as the forward direction, and then call the reversed () function:
When repeating a sequence in a certain order, use the sorted () function, which returns a new sorted list without modifying the original:
If you want to change the sequence that you are iterating in a loop (for example, repeat a specific item), we strongly recommend that you make a copy first. Loop a sequence does not implicitly make a copy. Slice recording makes this especially convenient:
5.7 more related conditions
The conditions of the while and if expressions can contain any operators, not just comparison.
The comparison operators in and not in check whether a value is in the sequence. The operator is and is not compares whether two objects are the same object. This is only for variable objects, such as lists. All comparison operators have the same priority, which is lower than all numerical operators.
Comparison can be linked together. For example, a <B = c tests whether a is less than B, and B is equal to C.
The comparison can be combined with the Boolean operator and or. The comparison result (or any other Boolean expression) can use the not inverse. The priority of these operators is lower than the comparison operators. Between them, not has the highest priority, or is the lowest, so a and not B or C and (A and (not B )) or C is equal. Parentheses can always be used to express the desired combination.
Boolean operators and or are called short-circuit operators. Their parameters are calculated from left to right. When the result is determined, the computation immediately stops. For example, if A and C are true but B is false, expression C is not calculated for A and B and C. When used for a common value rather than a Boolean value, the return value of the short-circuit operator is the last calculated parameter.
You can assign the values of the comparison and other boolean expressions to the variables. For example:
Note that, unlike C in Python, assignment values cannot appear in expressions. C programmers may complain that, in order to avoid a common category problem in C Programs, when you need equal sign =, a value = is entered.
5.8 comparison between SEQUENCES AND OTHER TYPES
Sequences of the same type can be compared. Compare the order in the dictionary. First, use the first pair of elements for comparison. If they are different, you can determine the comparison result. If they are the same, compare the second pair of elements until the elements of any sequence are used up. If the two elements to be compared are sequences of the same type, they are compared recursively by dictionary. If all elements are equal, the sequence is considered equal. If a sequence is a subsequence at the starting position of another sequence, the short sequence is a smaller one. The dictionary order uses Unicode-encoded vertices to sort individual characters for strings. Comparison examples of sequences of the same type:
Note: It is valid to use <and> to compare different types of objects, as long as the object can provide an appropriate comparison method. For example, the mixed numeric types are compared by their numerical values, and the index 0 is equal to 0.0. Otherwise, the interpreter will generate a type error instead of providing any sorting.
This article is the official website content translation, original address: http://docs.python.org/3/tutorial/datastructures.html