Getting Started with Python [series] on the basis of 07 days: Python data structures - Sequence

Built-python is the most common type of sequence lists, tuples and strings . (SEQ python is the most basic data structure, the data structure is a computer store, organize data.)

It also provides a dictionary and a set of data structures, but they belong to no sequence of data collection , the data can not be accessed by an index like the former position. python sequence number of each element has a (specific position of the element), this number is called the index , the index from index 0, so ...... 

This article focuses on the sequence of python and its practical application, to consolidate the fundamentals of grammar python .

 

 

First, the concept of sequence

 

Data structures: somehow combined set of data elements.

Sequence: The ID set combination of data elements together.

 

Second, the general characteristics and operation sequence

  1. Index : obtaining the n-th element value by [n]. n> 0 index direction from left to right ( zero ), n-<0 indexed from right to left ( at -1 ). Function call returns when the sequence can be directly indexed.

  2. Sections : with [a: b: c] Access [a, b) within a range of elements. a, b, c can be positive or negative air. a: start bit, b: stop bits, c: step. 

  3. Adding : only the same type of splice sequence.

  4. Multiplication : x times repeats.

  5. Check : Use in operator determines whether there is a member in the sequence. Returns a Boolean value (True | False)

  6. General built-in functions : len returns the number of elements within the sequence, min and max are the maximum and minimum return sequence elements

     

 

 

Three, python built sequence 1 - list

List of definitions

The form: [a, b, c, d], the sequence data may be another element, the element can be modified.

 

List Building

list () may be converted to a list of other sequences.

 

A list of basic operations

  1. Modify elements: selected directly assigned  ls [1] = 'e'

  2. Removing elements: del statement  del ls [1]

  3. Bulk editing elements: microtome assignment additions or deletions to the original data elements ls [1: 1] = ' ello'

     

A list of commonly used methods

  1. append: list of add at the end of a target (can be a list)

  2. clear: only empty, do not delete the list

  3. copy: = ls2 different and ls1, ls2 = ls1.copy (rear) ls2 modified without affecting ls1

  4. count: the number of computing elements appear

  5. extend: the end of a list of multiple values

  6. index: Finding an element in the list for the first time the index value

  7. insert: a location to add a list of objects ls.insert (2, 'a')

  8. pop: delete an element and returns that element, the default is to delete the last element 

    LIFO: ls.append (ls.pop ())

    FIFO: ls.append (ls.pop (0)) | ls.insert (0, ls.pop ())

  9. remove: delete the specified element in the list of the first occurrence

  10. reverse: Instead sort reverse.

    reversed (ls) function returns an iterator, list (reversed (ls)) can be converted to a listing

  11. sort: Sort sort (key, reverse) key: functions for sorting, reverse: True (descending) | False (in ascending order). sorted (ls, key, reverse), sorted list is returned

     

     

Four, python built Sequence 2 - tuple

Tuple defined

The form: (a, b, c, d), the element can not be modified.

Construction of tuples

Single values: 1, | (1)

Multi-valued: 1,2,3 | (1,2,3)

tuple () is converted to the other sequences tuple

Tuple role

python many built-in functions and the method returns a tuple, it can be used as keys in a map.

Five, python string built sequence 3--

String definitions

The form: 'abcd', the element can not be modified.

String Builder

join () method can be merged sequence strings, sep.join (seq): between each element of seq sep phase, into one string

String common method

  1. count: statistics

  2. find: Find whether a string exists, there is no return -1

  3. replace: replace the parameters :( character, content replacement, replacement of the number of times)

  4. strip: remove about blank, lstrip / rstrip box to the left / to the right spaces

  5. Split: split (character, number) Returns the list. Partition (), only the division of the position of the first occurrence, also dividing the tuple content itself is a single element, returns a tuple

  6. Case: capitalize () first character uppercase, title () string of each word capitalized, lower () / upper () all lowercase / uppercase whole

  7. Judge: startwith / endwith: determine the beginning and end characters. isalpha / isalnum / isdigit / isspace: Analyzing the whole string of letters / letters + numbers / digital full / empty Full

 

Using the sequence example Overview:

 

# Define a sequence of student
>>> stuinfo = [ 'liuwang', 'xuezhang', 'zuishuai', 18,20]

List adding:

 

# Define the student's name and age of the students, and then define a database of their own will join two lists

>>> stuname=['liuwang','xuezhang','zuishuai']
>>> stuage=[18,20,16]
>>> database=[stuname,stuage]
>>> database
[['liuwang','xuezhang','zuishuai'], [18, 20, 16]]

Generic sequence of operations using the index:

 

All the elements have sequence numbers, these numbers are zero, in ascending order, these elements are accessed via subscript to access, and this is the index number, for example:



>>> database
[['liuwang','xuezhang','zuishuai'], [18, 20, 16]]

>>> database[0]
['liuwang', '学长', 'zuishuai']
>>> database[1]
[18, 20, 16]



String sequence index #

>>> str='hello'
>>> str[0]
'h'
>>> str[1]
'e'

 

Note that neither index ways: we just use positive zero-based index,

When a negative index, Python does all from right to left, -1 is the last element of the sequence from the start, as follows:

 

 
#从最后一个元素开始
>>> str[-1]
'o'
#从倒数第二个元素开始
>>> str[-2]
'l'

 

2. Slice

 

The same index and the like, the slicing element is accessed through the operating range of the colon, for example:

 


# 构建一个序列tag,里面包含一个元素
>>> tag=['https://www.wakemeupnow.cn']

# 拿到这个元素后通过分片取出一个范围的值(示例域名是我的博客嘿嘿)
>>> tag[0][8:]
'www.wakemeupnow.cn'

Known from the above, to achieve desirable to provide a slicing two indices as a boundary, a right-left opening and closing section.

In addition to the above-described embodiment, the operation may be performed by the display mode:

2.1 slices shortcuts


>>> num[0:3]
# 取到前面3个数据
[1, 2, 3]

2.2 slicing operation steps

 

Slicing step may be provided to the element, to specify the appropriate step size acquired at the beginning and the end element, for example:

 


# 按照步长为2返回第1个和第6个之间的元素
>>> num[0:6:2]
[1, 3, 5]

 

Also note that step is negative traverse the entire sequence from the front to the tail element, the negative slice start index must be greater than the end index



>>> num[7:-1]
[8, 9]

When the starting index and ending index is negative it must be less than the beginning of the end of the index:

 


>>> num[-9:-1]
[2, 3, 4, 5, 6, 7, 8, 9]

For a positive step, Python will start sequence extracted from the head of the right elements, direct access to the last element, and for a negative step, it is beginning to extract elements from the left end of a sequence of direct extraction to the first one, E.g:



# 提取前6个元素,步长为2
>>> num[:6:2]
[1, 3, 5]
# 提取从后往前的8个元素,步长为2
>>> num[:2:-2]
[10, 8, 6, 4]

3 sequences are added

 

Sequence summing the plus sign "+" is connected between the operation sequence and the sequence:



>>> 'hello'+' 学长!'
'hello 学长!'

>>> [1,2,3]+['liuwang','学长']
[1, 2, 3, 'liuwang', '学长']

 

Note: Only the same type of sequence can connect operation.

 

4. sequence to be multiplied

 

A number x is generated by multiplying a sequence a new sequence of the original sequence will be reset to x times



>>> ['hello'+' world !']*3
['hello world !', 'hello world !', 'hello world !']

5. Membership

 

Check whether an element in a sequence in operator to check, in a condition check operator returns a Boolean value, returns true if it is true, otherwise it returns false, for example:



>>> str='hello'
>>> 'h' in str
True

>>> 'x' in str
False

6. The sequence length, the maximum and minimum

 

Sequence length, the maximum and minimum functions using the built-len, max, min detection, len returns the number of elements contained in the sequence, max and min are maximum and minimum return sequence elements



>>> len([11,34,23])
3
>>> max(11,34,23)
34
>>> min(11,34,23)
11

to sum up

This section to introduce the use of a sequence of Python data structures, to provide support engineers use Python, you can remove the corresponding element in the practical application of the project, today's knowledge is not hard to do, but need to firmly consolidated.

 

 

 
Published 374 original articles · won praise 179 · views 110 000 +

Guess you like

Origin blog.csdn.net/qq_41856814/article/details/104804019