Python programming (4)

zhaozj2021-02-08  224

Chapter 5 Python Data Structure

This chapter discusses some of the useful data types in more detail and introduces some new types.

5.1 list

There are other methods in the list data type. Below is all methods of the list object:

INSERT (i, x) ---- Insert an item at the specified location. The first independent variable is inserted in front of which element is inserted, and it is represented by the subscript. For example, A. INSERT (0, x) is inserted in front of the list, A.Nsert (LEN (A), X) is equivalent to A.Append (x). Append (x) ---- Equivalent to A. INSERT (LEN (A), X) Index (X) ---- looks for value X in the list and then returns the subscript of the element of the first value of x. An error was not found. Remove (X) ---- From the list, the first value is an element, can't find it. Sort () ---- The list element is sorted in situ. Note this method changes the list instead of returning a list of sorted. Reverse () ---- Reverse list elements. Change the list. Count (x) ---- Returns the number of times that appears in the list.

The following example uses all 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]

5.1.1 Function Program Design Tools

There are some function program design styles in Python, such as the form of the lambda we have seen. About the list There are three very useful built-in functions: filter (), map () and reduction ().

"Filter (function, sequence)" returns a sequence (as far as possible with the original), the sequence element is those that are filtered from the specified function in the original sequence, and the filter rules are "function (sequence elements) = true". FILTER () can be used to take out a subset of the satisfaction. For example, in order 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)" for each item of the specified sequence, the specified function, the result is a list of returns. Map () can be implicitly looped for sequences. For example, to calculate three times, available:

>>> DEF CUBE (X): Return X * x * x

...

>>> Map (Cube, Range (1, 11))

[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

There are multiple sequences as an argument. At this time, the specified function must also have the same number of arguments, and the function takes out the corresponding element from each sequence as an argument (if a sequence is more short, the value takes out is more short. Is None). If the specified function is none, MAP () regards it as a constant function that returns its own argument. In the case of a function, multiple sequences can be assigned multiple sequences, such as "MAP (None, List1, List2)" can combine two lists into a list of pairs. See here: >>> 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 to make a similar accumulation such, the function is a function of two sub-variables, and reduuce () gets a result of the first two call functions of the sequence, then lower the results and sequences. A call function gets a new result, so that the tail of the sequence is proceed. For example, to calculate 1 to 10 and:

>>> DEF ADD (X, Y): Return X Y

...

>>> Reduce (Add, Range (1, 11))

55

If there is only one value in the sequence, it returns this value, and the sequence generates an exception when empty. You can specify the third argument as the initial value. When there is an initial value, the original value will return to the initial value, otherwise the function is first effect on the initial value and sequence, and then the result and sequence will be used to proceed to the sequence tail. E.g:

>>> DEF SUM (SEQ):

... DEF Add (x, y): Return X Y

... Return Reduce (Add, SEQ, 0)

...

>>> SUM (Range (1, 11))

55

>>> SUM ([])

0

5.2 DEL statement

Above we see that the list of the list can be removed from the list, and we can also use the DEL statement to delete the item you specify. You can also remove a piece from the list (in front of us to use the segment to assume the segment). E.g:

>>> 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 A

The variable will be incorrect after the variable is deleted (unless it is assigned). Behind we will also see other applications of DEL.

5.3 Program and Sequence

We see that there are many common points, such as subscript and segment operations. They are all sequence data types. Because Python is a constantly developed language, other sequence data types may be added later. There is also a standard sequence data type called a preface table.

The preface is divided by a series of values, for example:

>>> T = 12345, 54321, 'Hello!'

>>> T [0]

12345

>>> T

(12345, 54321, 'Hello!') >>> # 表 allows nested:

... u = t, (1, 2, 3, 4, 5)

>>> U

((12345, 54321, 'Hello!'), (1, 2, 3, 4, 5)))

The output of the output is always surrounded by parentheses, so that the nested sequence table can be explained correctly. When entering the input, there is no parentheses, and it is often necessary to have parentheses (if the preface is part of a large expression).

There are many usage, such as, for example, (x, y) coordinate pairs, employee records in the database, and so on. The sequence table is the same as the string: no one of the preface tables is not allowed.

There is a special specification for 0 or 1 items when generating the order: The null sequence is indicated by a pair of empty brackets; there is only one of the programs to use one after another. (Refers to this value It is not enough in parentheses). This is not beautiful enough, but it is very effective. E.g:

>>> EMPTY = ()

>>> Singleton = 'Hello', # <- Note Trailing CommA

>>> LEN (EMPTY)

0

>>> LEN (Singleton)

1

>>> Singleton

('Hello',)

Statements T = 12345, 54321, 'Hello!' Is an example of the preface package: 12345, 54321 and 'Hello!' These values ​​are packaged into a preface. The opposite operation is also allowed, for example:

>>> x, y, z = t

This is called a preface to unpack. The number of variables on the left side of the order is equal to the length of the preface table. Note that multiple assignments are just the joint use of the preface packages and procedures. Sometimes the list is similar to operation, that is, the list is unpacking. As long as you write each variable into a list, you can unpack:

>>> a = ['spam', 'Eggs', 100, 1234]

>>> [A1, A2, A3, A4] = a

5.4 dictionary

Another useful data type built into Python is a dictionary. Dictionary is sometimes referred to as "associated memory" or "associated array" in other languages. Dictionary is not like sequence, it is not used in a range of numbers to index, but indexes with key values, key values ​​can be any non-variable type. Strings and values ​​can always make key values. If the program list contains only strings, the value or the preface, the order list can also be used for key values. The list cannot be used as a key value because the list can change the value in its Append () method.

It is best to regard the dictionary as a collection of unsorted "key values: value", which is different in the same dictionary. A pair of air braces produced an empty dictionary: {}. Add a comma-separated "key value: value" to the brace, which can be added to the initial key value and value pair within the dictionary, the dictionary is also displayed when the dictionary is displayed. The main operation of the dictionary is to save a value at a key value, and the corresponding value is found after a given key value. You can also delete a key value with Del: value. If a value is saved with an existing key value, the original vegetation is forgotten. Going to find an error with the non-existing key value.

Keys () method of the dictionary object returns a list of all key values ​​in the dictionary, and the order is random. When you need to sort, you only use the sort () method as long as the returned key value list is required. In order to check if a key value is in the dictionary, the HAS_KEY () method of the dictionary is used.

Below is a simple example of the dictionary:

>>> 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')

1

5.5 Further Discussion of Conditions

The conditions used in the While statement and the IF statement may include other operators in addition to comparison. Compare operators "IN" and "not in" can check if a value is in a sequence. The operator "IS" and "IS Not" compares whether the two objects are just the same object, which is meaningful for the object list. All comparison operations are the same, and the priority of comparison is lower than all numerical operations.

Comparison allows for connection, for example, a

Compares can be connected with logical operators and OR, comparison result (or any other logical expression) can be reversed with NOT. The logical operator is lower than all comparison operators, in the logical operator, the NOT priority is the highest, the OR is the lowest, so "a and not b or c" should be explained "(a and (not b)) or C ". Of course, it can be used to represent the desired combination conditions.

Logical operators AND and OR are called "short circuit" operators: the expression on both sides of the operator is to calculate the left, if the result is known to the left, the overall result is not known, the right expression is not calculated. For example, if A and C are true and B is false, "a and b and c" does not calculate the expression C. Generally, the value returned when the operation result of the short-circuit operator is not used as a logic value, the value of the expression of the final evaluation.

The results of comparison or other logical expressions can be assigned to one variable. E.g:

>>> String1, String2, String3 = ',' Trondheim ',' Hammer Dance '

>>> Non_null = String1 or string2 or string3

>>> Non_NULL

'Trondheim'

Note Python and C are different, and assignments cannot be performed in the expression.

5.6 Sequence and other types of comparisons

Sequence objects can be compared to other symptoms of the same sequence type. Compare the use of the word: first compare the first two items, if these two different results can be determined; if these two are the same, the following two are compared, so that there is a sequence to the end. If a two items itself are also the same type of sequence, the recursive Dictionary is compared. If all of the two sequences are equal, the two sequences are equal. If a sequence is an initial subsequence of another sequence, a short one is a smaller one. The character of the string is done in the ASCII order of each character. Here are some examples of sequence comparisons:

(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 different types of objects are also legitimate. The result is determined, but there is no significance: Different types are sorted by the type of name. Therefore, the list (list) is always smaller than the string, the string is always smaller than the order, and so on. But the program cannot rely on such comparisons, and the language implementation may change. Different numeric types can be compared by value, so 0 is equal to 0

转载请注明原文地址:https://www.9cbs.com/read-2256.html

New Post(0)