Document directory
- 1.1 function programming tools
1 List
There are other methods for listing data types. The following are all the methods for listing objects:
- Insert (I, x) ---- insert an item at a specified position. The first independent variable is inserted before the element and is represented by the lower mark. For example, if a. insert (0, x) is inserted before the list, A. insert (LEN (A), X) is equivalent to a. append (X ).
- Append (x) ---- equivalent to a. insert (LEN (A), X)
- Index (x) ---- search for the value x in the list and return the subscript of the first element with the value x. An error occurred while not found.
- Remove (x) ---- Delete the first element with the value of X from the list. An error occurred when the element cannot be found.
- Sort () ---- sort list elements in the original position. Note that this method changes the list instead of returning the sorted list.
- Reverse () ---- sorts list elements in reverse order. Change the list.
- Count (x) ---- returns the number of times X appears in the list.
The following example uses all the list methods:
>>> a = [66.6, 333, 333, 1, 1234.5]>>> print a.count(333), a.count(66.6), a.count('x')2 1 0>>> a.insert(2, -1)>>> a.append(333)>>> a[66.6, 333, -1, 333, 1, 1234.5, 333]>>> a.index(333)1>>> a.remove(333)>>> a[66.6, -1, 333, 1, 1234.5, 333]>>> a.reverse()>>> a[333, 1234.5, 1, 333, -1, 66.6]>>> a.sort()>>> a[-1, 1, 66.6, 333, 333, 1234.5]1.1 function programming tools
Python has some functional programming style things, such as the lambda form we saw earlier. The list contains three very useful built-in functions: Filter (), map (), and reduce ().
"Filter (function, sequence)" returns a sequence (as much as possible with the original type). The sequence elements are those filtered by the specified function in the original sequence, the filter rule is "function (sequence element) = true ". Filter () can be used to retrieve a subset that meets the condition. For example, to calculate some prime numbers:
>>> def f(x): return x % 2 != 0 and x % 3 != 0...>>> filter(f, range(2, 25))[5, 7, 11, 13, 17, 19, 23]
"Map (function, sequence)" calls the specified function for each item of the specified sequence, and the result is a list composed of return values. Map () can perform an implicit loop on the sequence. For example, to calculate the Power of Three, available:
>>> def cube(x): return x*x*x...>>> map(cube, range(1, 11))[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
Multiple sequences can be used as independent variables. In this case, the specified function must have the same number of independent variables, the function extracts the corresponding element from each sequence column as the independent variable for calling (if a sequence is shorter than other columns, the value is none ). If the specified function is none, map () treats it as a constant function that returns its own independent variables. When the function uses none to specify multiple sequences, multiple sequences can be combined, for example, "map (none, list1, list2) you can combine the two lists into a list of paired values. See the following example:
>>> seq = range(8)>>> def square(x): return x*x...>>> map(None, seq, map(square, seq))[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49)]
"Reduce (function, sequence)" is used for operations similar to accumulate. Here the function is a function of two sub-variables, reduce () first, call the function of the first two items of the sequence to get a result, and then obtain a new result for the result and the next call function of the sequence, so that it is carried to the end of the sequence. For example, to calculate the sum of 1 to 10:
>>> def add(x,y): return x+y...>>> reduce(add, range(1, 11))55
If there is only one value in the sequence, this value is returned. If the sequence is null, exceptions are generated. You can specify the third independent variable as the initial value. If there is an initial value, the initial value will be returned for the null sequence function. Otherwise, the function first acts on the initial value and the first item of the sequence, and then acts on the result and the next item of the sequence, so as to the end of the sequence. For example:
>>> def sum(seq):... def add(x,y): return x+y... return reduce(add, seq, 0)... >>> sum(range(1, 11))55>>> sum([])0
2 del statement
As we can see above, the remove () method of the list can delete an item with a certain value from the list, and we can also use the del statement to delete the item with the specified lower mark. You can also use the del statement to delete a part from the List (we used to delete the part by assigning an empty list to the part ). For example:
>>> a[-1, 1, 66.6, 333, 333, 1234.5]>>> del a[0]>>> a[1, 66.6, 333, 333, 1234.5]>>> del a[2:4]>>> a[1, 66.6, 1234.5]
Del can also be used to delete the entire variable, for example:
>>> Del
When a variable is deleted and then referenced, an error occurs (unless it is assigned another value ). Later we will see some of Del's applications.
3-order tables and Sequences
We can see that the list and string have many things in common, such as subscript and fragment operations. They all belong to the sequence data type. Because python is a developing language, it may be added to other sequence data types in the future. There is also a standard sequence data type, called a sequence table (tuple ).
A sequence table is composed of a series of values separated by commas (,). For example:
>>> T = 12345,543 21, 'Hello! '>>> T [0] 12345 >>> T (12345,543 21, 'Hello! ') >>># Allowed nesting of the sequence table :... U = T, (1, 2, 3, 4, 5)> U (12345,543 21, 'Hello! '), (1, 2, 3, 4, 5 ))
The output sequence table is always surrounded by parentheses, so that the nested sequence table can be correctly interpreted. The input can contain parentheses or no parentheses. When it is often necessary to have parentheses (if the sequence table is part of a large expression ).
Sequence tables are useful, such as (x, y) Coordinate pairs, employee records in databases, and so on. A sequence table and a string are immutable: A value assignment to a sequence table is not allowed.
When generating a sequence table, there are special rules for a sequence table with 0 or 1 items: An empty sequence table is represented by a pair of empty parentheses; only one sequence table is represented by a side following a shake (it is not enough to put this value in parentheses ). This is not beautiful enough, but it is very effective. For example:
>>> empty = ()>>> singleton = 'hello', # <-- note trailing comma>>> len(empty)0>>> len(singleton)1>>> singleton('hello',)
Statement t = 12345,543 21, 'Hello! 'Is an example of sequential table packaging: 12345,543 21 and 'Hello! 'These values are packaged into a sequence table. The opposite operation is allowed, for example:
>>> X, y, z = T
This is called the sequence table solution package. The number of variables on the left of the equal sign must be equal to the length of the sorted table. Note that multiple values are only used in combination with sequence table packaging and sequence table unpacking. You can perform similar operations on the list, that is, unpackage the list. You only need to write the variables into a list to unpack them:
>>> a = ['spam', 'eggs', 100, 1234]>>> [a1, a2, a3, a4] = a
4. Dictionary
Another useful data type built in python is dictionary. In other languages, dictionaries are sometimes called "correlated memory" or "correlated array ". Unlike sequences, a dictionary is not used to index numeric subscripts within a range. Instead, it is used to index key values. The key value can be of any immutable type. String and value can always be used as key values. If the table contains only strings, values, or orders, the table can also be used as a key value. The list cannot be used as a key value because the list can be changed locally using its append () method.
It is best to regard the dictionary as a series of unordered "key value: Value" sets. The key values in the same dictionary are different from each other. A pair of empty braces generates an empty dictionary :{}. The "key-value: Value" pairs separated by commas can be added to the dictionary with the initial key-value pair. The dictionary is also displayed in the output. The main operation of the dictionary is to save a value for a key value, and find the corresponding value after the key value is given. You can also use del to delete a key-value pair. If you save a value with an existing defined key value, the original vegetation is forgotten. An error occurred when searching with a nonexistent key value.
The keys () method of the dictionary object returns a list of all key values in the dictionary. The order is random. When sorting is required, you only need to use the sort () method for the returned key value list. To check whether a key value is in the dictionary, use the has_key () method of the dictionary.
The following is a simple example of dictionary usage:
>>> tel = {'jack': 4098, 'sape': 4139}>>> tel['guido'] = 4127>>> tel{'sape': 4139, 'guido': 4127, 'jack': 4098}>>> tel['jack']4098>>> del tel['sape']>>> tel['irv'] = 4127>>> tel{'guido': 4127, 'irv': 4127, 'jack': 4098}>>> tel.keys()['guido', 'irv', 'jack']>>> tel.has_key('guido')15. Further discussion of the conditions
In addition to comparison, the conditions used in the while statement and if statement can contain other operators. Compared with the comparison operators "in" and "not in", you can check whether a value is in a sequence. The operators "is" and "is not" compare whether two objects happen to be the same object. This variable object such as the object list makes sense. All comparison operations have the same priority, while comparison operations have lower priority than all numerical operations.
For example, a <B = C checks whether a is less than or equal to B and B is equal to C.
Comparison can be connected by logical operators and or. Comparison results (or any other logical expressions) can be reversed by not. Logical operators are lower than all comparison operators. Among logical operators, not has the highest priority, or has the lowest priority, therefore, "A and not B or C" should be interpreted as "(a and (not B) or C ". Of course, brackets can be used to indicate the combination conditions.
Logical operators and or are short-circuit operators: the expressions on both sides of the operators calculate the left side first. If the result of the left side is known, the overall result is known and the expression on the right is no longer calculated. For example, if expression A and C are true and expression B is false, expression C is not calculated for expression A and B and C. Generally, when the result of the short-circuit operator is not used as a logical value, the return value is the value of the final evaluated expression.
You can assign the result of a comparison or other logical expressions to a variable. For example:
>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'>>> non_null = string1 or string2 or string3>>> non_null'Trondheim'
Note that python and C are different, and values cannot be assigned in expressions.
6. Comparison between SEQUENCES AND OTHER TYPES
Sequence objects can be compared with other objects of the same sequence type. Use the Lexicographic Order for comparison: first compare the first two items. If the two items are different, the result can be determined. If the two items are the same, compare the following two items, until there is a sequence to the beginning. If two items are of the same type, recursive lexicographic comparison is performed. If all the items in the two ordinal columns are equal, the two sequences are equal. If a sequence is an initial subsequence of another sequence, the shorter one is a smaller one. The lexicographic orders of strings are compared according to the ASCII order of each character. The following are examples of sequence comparison:
(1, 2, 3) < (1, 2, 4)[1, 2, 3] < [1, 2, 4]'ABC' < 'C' < 'Pascal' < 'Python'(1, 2, 3, 4) < (1, 2, 4)(1, 2) < (1, 2, -1)(1, 2, 3) = (1.0, 2.0, 3.0)(1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
Note that the comparison of different types of objects is also valid currently. The results are definite but meaningless: different types are sorted by type names. Therefore, the list is always smaller than the string, and the string is always smaller than the tuple. However, the program cannot rely on such comparison rules, and the language implementation may change. Different numeric value types can be compared by numerical value, so 0 is equal to 0.0, and so on.