[Python] grammatical basis-7, sequence structure

1.7 Sequence structure

Mutable objects and mutable objects

There are three main types of built-in data types in Python:

  • Number : integer, floating point

  • Sequence: string, list, tuple, set

  • Mapping : Dictionary

According to whether it can be modified in situ, it is divided into two categories:

  • Immutable objects (numbers, strings, tuples, immutable collections)

    No object type in the immutable classification supports in-situ modification, but you can create new objects and assign the results to variables

  • Mutable objects (lists, dictionaries, mutable collections)

    On the contrary, mutable types can always be modified in place through related operations without the need to create new data objects

Sequence of general operations

Index, slice, add, multiply, iteration, and membership check

Index operation

All elements in the index are numbered (subscripts), subscripts start counting from 0, of course, in Python, you can also use negative subscripts to access elements, the subscript of all the last element is -1 (the last one)

>>> word = "hello"
>>> word[0]
'h'
>>> word[2]
'l'
>>> word[-1]
'o'
>>> word[-5]
'h'
>>> word[10]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

For the literal quantity of the sequence, you can directly use the subscript operation, without the need for variables

>>> "hello"[3]
'l'
>>> "hello"[-1]
'o'

Slice operation

Indexing is to go one piece of data at a time, and slicing is to take one piece of data at a time. The start and end must be determined, including the step size (default is 1)

>>> word = "12345678"
>>> word[0:3]
'123'
>>> word[-3:-1]
'67'

Whether it is a positive index or a negative index, the order must be guaranteed

>>> word[1:8:2]
'2468'
>>> word[-6:-2:3]
'36'
>>> word[7:1:-2]
'864'
>>> word[-1:-5:-1]
'8765'
>>> word[-1:-5:1]
''
>>> word[:]
'12345678'
>>> word[2:]
'345678'
>>> word[:5]
'12345'
>>> word[-5:]
'45678'
>>> word[-3::-1]
'654321'

The step size is positive, increasing from the beginning to the end

The step size is negative, starting to ending decreases

>>> text = "我爱你"
>>> text = text[::-1]
>>> text
'你爱我'
>>> text = text[-1:-4:-1]
>>> text
'我爱你'

Add operation

Refers to the merging of two sequences, which will generate a new sequence object without changing the value of the original sequence

>>> s1 = "abc"
>>> s2 = "ABC"
>>> s1 + s2
'abcABC'
>>> s1
'abc'
>>> s2
'ABC'

Addition can only be performed between sequences of the same type

Multiply operation

Multiply the sequence by the number x, and repeat this sequence x times to create a new sequence

>>> s1
'abc'
>>> s3 = s1 * 3
>>> s3
'abcabcabc'

Iterative operation

You can iterate each element in the sequence in the for loop, or iterate over the subscripts to get the elements

>>> s1
'abc'
>>> for i in s1:
...     print(i)
...
a
b
c
>>> for i in range(len(s1)):
...     print(s1[i])
...
a
b
c
​
>>> word[0] = '9'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

Membership check operation

Is to verify whether a data element exists in the current sequence

>>> '8' in word
True
>>> 8 in word
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not int
​
>>> '10' not in word
True
>>> '10' in word
False
>>> 5 in range(0,10)

String

Immutable object, an ordered collection of characters, used to store and represent basic text information

Strings are not allowed to modify the value in situ, and the length of the string cannot be modified once it is defined

If you really want to modify the string, you can only create a copy of the string, and the content of the copy is the modified content

Test string method:

  • isalnum(): Verify that only numbers and letters are included

  • isalpha(): Verify that only letters are included

  • isdigit(): verify that only numbers are included

  • isidentifier(): verify whether it is a legal identifier

  • islower(): verify whether the letters in the content are all lowercase

  • isupper(): verify whether the letters in the content are all uppercase

  • isspace(): verify whether only contains spaces

Search string method:

  • endswith(str): verify whether the end of the str suffix

  • startswith(str): verify whether the prefix starts with str

  • find(str): Returns the first occurrence of str from left to right, or -1 if it does not exist. rfind() instead

  • index(str): The function is the same as find, if it does not exist, there will be an exception

  • count(str): Record the number of occurrences of str, without overwriting

Convert string:

  • capitalize(): Copy the string and capitalize the first letter

  • lower(): convert all letters to lowercase

  • upper(): convert all letters to uppercase

  • title(): Copy the string and capitalize the first letter of each word

  • swapcase(): Copy the string, convert lowercase to uppercase, and uppercase to lowercase

  • replace(a,b): Replace a in the original string with b to generate a new string

  • split(str): Use str as a separator to split the string, and the result is a list of characters

  • partition(str): take str as the central part, divide the string into two parts, left and right

Remove string spaces:

  • lstrip(): Remove the space on the left side of the string

  • rstrip()

  • strip()

Format string:

  • center(w): Use w as the width to display the content in the center

  • light()

  • rjust ()

>>> "123abc".isalnum()
True
>>> "我爱你123abc*!&@%#^&%&".isalnum()
False
>>> "abc".isalpha()
True
>>> "123".isalpha()
False
>>> "123abc".isalpha()
False
>>> "123".isdigit()
True
>>> "abc".isdigit()
False
>>> "sum".isidentifier()
True
>>> "123abc".isidentifier()
False
>>> "abc".islower()
True
>>> "ABC".islower()
False
>>> "123abc".islowe()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'islowe'
>>> "123abc".islower()
True
>>> "     ".isspace()
True
>>> " ad asd asd".isspace()
False
>>> "123,456,789".find("456")
4
>>> "123,456,789".rfind("456")
4
>>> word = "123456789456"
>>> word.find("456")
3
>>> word.rfind("456")
9
>>> word
'123456789456'
>>> word.index("123")
0
>>> word.index("456")
3
>>> word.find("666")
-1
>>> word.index("666")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> "121212121".count("121")
2
>>> name = "anglababy"
>>> name.capitalize()
'Anglababy'
>>> name
'anglababy'
>>> "Andy Mimi Lala".lower()
'andy mimi lala'
>>> "Andy Mimi Lala".lower().upper()
'ANDY MIMI LALA'
>>> "mynameishaha".title()
'Mynameishaha'
>>> "my name is haha".title()
'My Name Is Haha'
>>> s= "my name is haha".title()
>>> s
'My Name Is Haha'
>>> s.swpacase()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'swpacase'
>>> s.swapcase()
'mY nAME iS hAHA'
>>> s = "宇智波萨斯尅,宇智波马达啦,宇智波一大气,宇智波欧鼻头"
>>> s.replace("宇智波","千手")
'千手萨斯尅,千手马达啦,千手一大气,千手欧鼻头'
>>> s
'宇智波萨斯尅,宇智波马达啦,宇智波一大气,宇智波欧鼻头'
>>> s.split(",")
['宇智波萨斯尅', '宇智波马达啦', '宇智波一大气', '宇智波欧鼻头']
>>> l = s.split(",")
>>> l[1]
'宇智波马达啦'
>>> "莫西莫西海雅库摩多摩多".partition("雅")
('莫西莫西海', '雅', '库摩多摩多')
>>> "123456789".partition("456")
('123', '456', '789')
>>> "    123".lstrip()
'123'
>>> "123   ".rsrtip()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'rsrtip'
>>> "123   ".rstrip()
'123'
>>> "    8798    ".strip()
'8798'
>>> "I Love You".center(16)
'   I Love You   '
>>> s = "abc"
>>> s.center(10)
'   abc    '
>>> s.ljust(10)
'abc       '
>>> s.rjust(10)
'       abc'

List

Lists are the most flexible type of ordered collection objects in Python. Unlike strings, lists can contain any kind of objects: numbers, strings, and even lists. Similarly, unlike strings, lists are mutable objects, and they all support operations that are modified in place, and the length of lists is also variable.

Variable: In the list space, the address stored and pointing to a certain data object is variable

How the list was created

Specify the element directly

>>> [1,2,3,4,5]
>>> l = [1,2,3,4,5]

Specifying the length but not specifying the elements is equivalent to creating an empty list of length n but no data object addresses

>>> l = [None] * 10
>>> l
[None, None, None, None, None, None, None, None, None, None]

Use the list function to convert other data into a list. These data must be iterable. The iterable can be operated by the for loop.

>>> list() # 得到一个长度为0的列表
[]
>>> l = list("abcd")
>>> l
['a', 'b', 'c', 'd']
>>> l[0]
'a'
>>> l[-1]
'd'
>>> l = list(range(0,5))
>>> l
[0, 1, 2, 3, 4]
>>> l  =list(1234)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

List specific operations

  • Modify elements

    >>> l
    [0, 1, 2, 3, 4]
    >>> l[0]=5
    >>> l
    [5, 1, 2, 3, 4]

     

  • Slice modification

    >>> l = [1,2,3,4,5,6,7,8,9]
    >>> l
    [1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> l[3:7] = [666,888,999]
    >>> l
    [1, 2, 3, 666, 888, 999, 8, 9]

     

  • Delete operation

    >>> l
    [1, 2, 3, 666, 888, 999, 8, 9]
    >>> del l[3]
    >>> l
    [1, 2, 3, 888, 999, 8, 9]
    >>> del l[-3]
    >>> l
    [1, 2, 3, 888, 8, 9]
    >>> del l   # 删除列表对象 连着变量也一同删除
    >>> l
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'l' is not defined

     

Built-in functions for lists

  • append(): Add an element object to the end of the list

    >>> l = [1,2,3]
    >>> l.append(4)
    >>> l
    [1, 2, 3, 4]
    >>> l1 = [1,2,3,4]
    >>> l2 = [5,6,7,8]
    >>> l1.append(l2)
    >>> l1
    [1, 2, 3, 4, [5, 6, 7, 8]]
    >>> l1.append("abc")
    >>> l1
    [1, 2, 3, 4, [5, 6, 7, 8], 'abc']

     

  • clear(): Clear the list, it does not mean deleting the list object

    >>> l.clear()
    >>> l
    []

     

  • copy(): Copy a new list object, consistent with the original list content, and return the address of the new list

    >>> l1 = [1,2,3,4]
    >>> l2 = l1
    >>> l2[0] = 5
    >>> l1
    [5, 2, 3, 4]
    >>> l2 = l1.copy()
    >>> l1
    [5, 2, 3, 4]
    >>> l2
    [5, 2, 3, 4]
    >>> l2[0]=10
    >>> l1
    [5, 2, 3, 4]
    >>> l2
    [10, 2, 3, 4]

     

  • count(): Count the number of times an element appears in the list

    >>> l = [1,1,2,3,1,2,3,4,3,2,1,1,2]
    >>> l.count(2)
    4

     

  • extend(): Extend the contents of other lists to the current list (add all the elements in the latter to the current list in turn)

    >>> l1 = [1,2,3,4]
    >>> l2 = [5,6,7,8]
    >>> l1.extend(l2)
    >>> l1
    [1, 2, 3, 4, 5, 6, 7, 8]
    >>> l2
    [5, 6, 7, 8]
    >>> l1.extend("abc")
    >>> l1
    [1, 2, 3, 4, 5, 6, 7, 8, 'a', 'b', 'c']
    >>> l1.extend(123)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'int' object is not iterable
    
    #如何理解extend?
    lst = []
    def extend(lter):
        for i in Iter:
            lst.append(i)

    Different from adding two sequences, adding two sequences directly creates a new sequence object

  • index(): Returns the corner index of the element from left to right, throws an exception if it does not exist

    >>> l = [1,2,3,4]
    >>> l.index(3)
    2
    >>> l.index(5)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: 5 is not in list
    ​
    >>> l.find(3)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'list' object has no attribute 'find'

     

  • insert(): Insert an element at a certain position, if the corner mark is out of bounds, if it is a negative number, it is the penultimate number; if the corner mark is greater than the length of the list, add it at the end

    >>> l
    [1, 2, 3, 4]
    >>> l.insert(2,5)
    >>> l
    [1, 2, 5, 3, 4]
    >>> l.insert(10,6)
    >>> l
    [1, 2, 5, 3, 4, 6]
    >>> l.insert(-2,7)
    >>> l
    [1, 2, 5, 3, 7, 4, 6]

     

  • pop(): delete an element at the end of the list, pop the stack; append is understood as pushing the stack

    >>> l = [1,2,3,4]
    >>> l.append(5)
    >>> l
    [1, 2, 3, 4, 5]
    >>> l.pop()
    5
    >>> l
    [1, 2, 3, 4]

     

  • remove(): delete the first specified element from left to right

    >>> l
    [1, 2, 3, 4]
    >>> l.remove(4)
    >>> l
    [1, 2, 3]
    >>> l.remove(2)
    >>> l
    [1, 3]
    >>> l = [1,1,1,2,2,3,3]
    >>> l.remove(1)
    >>> l
    [1, 1, 2, 2, 3, 3]

     

  • reverse(): reverse the list

    >>> l.reverse()
    >>> l
    [3, 3, 2, 2, 1, 1]

     

  • sort(): sort

    >>> l = [3,2,9,1,6,5,7,4,8]
    >>> l.sort()
    >>> l
    [1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> l.reverse()
    >>> l
    [9, 8, 7, 6, 5, 4, 3, 2, 1]

     

List comprehension

Is to create a list through a for loop statement

>>> l1 = [1,2,3,4,5,6,7,8,9,10]
>>> l1 = list(range(1,11))
>>> l1
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> l1 = [x for x in range(1,11)]
>>> l1
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> l1 = [x for x in range(1,21) if x%3==0 ]
>>> l1
[3, 6, 9, 12, 15, 18]
>>> l2 = [x/2 for x in l1]
>>> l2
[1.5, 3.0, 4.5, 6.0, 7.5, 9.0]

Binary search algorithm

The premise is that our sequence must be ordered (increasing, decreasing)

# 二分查找
def binarySearch(lst, key):
    min_index = 0
    max_index = len(lst) - 1
    mid_index = (min_index + max_index) // 2
    while lst[mid_index] != key:
        if lst[mid_index] < key:
            min_index = mid_index + 1
        elif lst[mid_index] > key:
            max_index = mid_index - 1
        if min_index > max_index:
            return -1
        mid_index = (min_index + max_index) // 2
    return mid_index
​
lst = [x for x in range(1,13)]
print(binarySearch(lst,9))
print(binarySearch(lst,1))
print(binarySearch(lst,8.5))
print(binarySearch(lst,15))
lst = [x ** 2 for x in range(1,13)]
print(binarySearch(lst,121))
print(binarySearch(lst,120))

 

Select sorting algorithm

def selectionSort(lst):
    for i in range(len(lst) - 1):
        for j in range(i+1,len(lst)):
            if lst[i] > lst[j]:
                lst[i],lst[j] = lst[j],lst[i]
                """
                temp = lst[i]
                lst[i] = lst[j]
                lst[j] = temp
                """
lst = [5,1,9,8,2,6,7,4,3]
selectionSort(lst)
print(lst)
 

Bubble sort algorithm

def bubbleSort(lst):
    for i in range(len(lst) - 1):
        for j in range(len(lst) - 1 - i):
            if lst[j] > lst[j + 1]:
                lst[j], lst[j + 1] = lst[j + 1], lst[j]
lst = [5,1,9,8,2,6,7,4,3]
bubbleSort(lst)
print(lst)

 

Insertion sort algorithm

def insertionSort(lst):
    for i in range(1,len(lst)):
        e = lst[i]
        j = i
        while j > 0 and lst[j - 1] > e:
            lst[j] = lst[j - 1]
            j -= 1
        lst[j] = e
lst = [5,1,9,8,2,6,7,4,3]
insertionSort(lst)
print(lst)

 

Counting sorting algorithm

def countingSort(lst):
    minVal = min(lst)
    maxVal = max(lst)
    temp = [0] * (maxVal - minVal + 1)
    offset = minVal
    for number in lst:
        temp[number - offset] += 1
    i = 0
    for index in range(len(temp)):
        for k in range(temp[index]):
            lst[i] = index + offset
            i += 1
​
lst = [5,1,9,8,2,6,7,4,3]
countingSort(lst)
print(lst)

 

Base sorting algorithm

import random
def getIndex(num,r):
    if len(str(num)) < r:
        return 0
    return int(str(num)[-r])
​
def radixSort(lst):
    maxVal = max(lst)
    radix = len(str(maxVal))
    temp = [None] * 10
    for i in range(10):
        temp[i] = []
​
    # 1个位 2十位 3百位
    for r in range(1,radix + 1):
        for num in lst:
            temp[getIndex(num,r)].append(num)
        i = 0
        for k in range(len(temp)):
            if len(temp[k]) != 0:
                for j in range(len(temp[k])):
                    lst[i] = temp[k][j]
                    i += 1
                temp[k].clear()
lst = []
for i in range(20):
    lst.append(random.randint(1,300))
radixSort(lst)
print(lst)

Tuple

It is a kind of sequence like a list, enclosed in parentheses()

A tuple is an immutable sequence, which can be understood as an immutable list

Except that the internal elements cannot be modified (addition, deletion, modification), other usage is similar to the list

>>> t = ()
>>> type(t)
<class 'tuple'>
>>> t = (1)
>>> type(t)
<class 'int'>
>>> t = (1,)
>>> type(t)
<class 'tuple'>
>>> t = (1,2,3)
>>> type(t)
<class 'tuple'>
>>> t = 1,2,3,4,5
>>> type(t)
<class 'tuple'>
>>> t = "你好","世界","哈哈"
>>> type(t)
<class 'tuple'>
>>> l = [1,2,3,4,5]
>>> type(l)
<class 'list'>
>>> t = tuple(l)
>>> t
(1, 2, 3, 4, 5)
>>> t = tuple("abcde")
>>> t
('a', 'b', 'c', 'd', 'e')

Same operations for elements and lists

  • count()、index()

  • len()、max()、min()、tuple()

>>> t = (1,2,3,4,5)
>>> max(t)
5
>>> min(t)
1
>>> len(t)
5
>>> t.count(5)
1
>>> t.index(3)
2
>>> t.sort()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'sort'
>>> t.find(3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'find'

Operations not allowed in tuples

  • Modify and add elements

  • Delete an element (but you can delete the entire tuple)

  • All methods that modify the internal elements of the tuple

>>> t.append(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'
>>> t.remove(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'remove'
>>> t
(1, 2, 3, 4, 5)
>>> t[0] = 666
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> del t[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object doesn't support item deletion
>>> del t
>>> t
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 't' is not defined

A tuple only guarantees that its first-level child elements are immutable. For nested elements, it is not guaranteed to be immutable

To put it bluntly, it means that the address of the object stored in the tuple is immutable

>>> t = (1,2,[3,4])
>>> t[0] = 666
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> t[2] = [5,6]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> t[2][0] = 5
>>> t[2][1] = 6
>>> t
(1, 2, [5, 6])
>>> id(t[2])
53493544
>>> t[2].append(7)
>>> t
(1, 2, [5, 6, 7])
>>> id(t[2])
53493544

Therefore, when using tuples, try to use the data types of immutable objects such as numbers, strings and tuples as elements

When do you usually use it? Once the data is determined and cannot be changed, use

>>> address = ("172.16.20.222","8080") # IP地址与端口号绑定

 

Guess you like

Origin blog.csdn.net/trichloromethane/article/details/108267507