We mentioned the built-in numeric and string types in Python data types earlier. Today, learn about the sequence data type of Python. You should know that there is no data structure of array in Python, nor does it provide the function of directly creating array, but you can use the built-in sequence data type to realize some functions of array.
1, What is a sequence data type?
Sequence data type is a basic data structure in Python. It is a set of sequential elements.
This collection can have multiple elements or no elements.
Generally speaking, it includes tuple s, list s, str ings, and byte data (bytes and byte array)
If it is divided according to the immutability of objects
Variable sequence: list, byte array
Immutable sequence: string, tuple and byte sequence
2, Basic operation of sequence data type
1. General method of sequence
Built in functions supporting sequence types: len(), max(), min(), sum(). When using the sum () function
It must be a numeric sequence. If there is a non numeric sequence, TypeError will be thrown. For string and number of bytes
It is also believed to lead to this result. Other functions select characters in dictionary order when using.
2. Access data through index
Each type in the sequence is an object that can be iterated. You can directly use the for loop to iterate to obtain each data.
You can also obtain the data at the specified location through the subscript index. The first element of the sequence is X, the last element of the sequence
The element is X[len(X)-1]. The subscript of the sequence is out of bounds or not an integer will cause an exception.
The sequence also supports slicing operations (as follows)
st="asfdcac" #Print all data print(st[::]) #Print strings in reverse order print(st[-1::-1])
3. Splice sequences of the same type
A sequence can use the operator + to connect two sequences to form a new sequence object.
The sequence can also be repeated by *.
4. Judge sequence members
As mentioned earlier in this article, you can use loops to iterate the sequence and find out each element
In addition to this function, Python can directly determine whether a sequence contains a member
The syntax rules are as follows:
x in s [True if x is in sequence S]
x not in s [True if x is not in sequence S]
s.count(x) [count the number of times X appears in sequence S]
s.index(X) [find the coordinate where X appears for the first time in s, and report an error if it cannot be found]
5. Sequence sorting
Through the built-in function sorted(), you can sort the sequence and return the sorted results.
def sorted(*args, **kwargs):
Here, an iterative sequence can be passed. Reverse can specify ascending or descending order. When reverse is
When True, the sorting result is in descending order. The key parameter is a function used to calculate and compare key values
6. Built in functions all() and any()
These two functions are used to judge whether all data is True
For all(), the result is True only when all members are True
For any(), the result is True as long as any member is True
7. Sequence splitting
① Split the sequence with a finite number of variables
In this method, the number of members of the sequence to be determined is consistent with the number of accepted variables.
Variable 1,Variable 2,Variable 3=sequence
② Split variable with uncertain number of members
This method uses and accepts members at a specific position in the sequence, and uses * to accept uncertain number of member variables.
Variables controlled by * are allowed to appear only once each time.
For example: mystr="nfklsdnfj0sd.....asdfl" s1,*args,s2=mystr here s1,s2 Will receive separately n And l The rest will make args Accept.
Introduction to the list
As mentioned earlier, the list is a variable sequence, which means that the list object itself can be modified or deleted directly
List is also a set of ordered data structures in Python. There is no array in Python. You can use list as array (✪) ω ✪)
1. Create a list
There are three ways
1. Create literal directly
2. Use list() and iteratable objects to create
3. List parsing expression
The code is as follows:
# Direct declaration lis0=list(i for i in range(0,101,10)) print(lis0) lis1=[1,2,3,4] # Iterator declaration lis2=[ i for i in range(0,101,10)] print(lis1,lis2) #Literal lis3=['Hello',123,'print',bool] print(lis3) '''
2. Add data to the list
The code is as follows:
# Add directly at the end of the list lis1.append(2) print(lis1) # Adding elements by slicing method (directly appending a part of the elements of another list) the memory address remains unchanged print(id(lis1)) lis1.extend(lis2) lis1.extend(lis2[1:5]) print(lis1,id(lis1)) # Inserts the specified element 999 at the specified location lis1.insert(1,999) print('11111111111',lis1)
3. Delete data in the list
The code is as follows:
# Nothing is filled in. The last element of the list is deleted by default lis1.pop() print(lis1) # Deletes the specified subscript element in the list lis1.pop(1) print(lis1) # Deletes the specified element lis1.remove(80) print(lis1) # Delete elements by slicing # The address of the list will change after the element is deleted by slicing method***** print(id(lis1),id(lis1[1:4]),lis1[1:4]) lis1[1:4] # clear list lis1.clear() print(lis1) # Delete the list (an error will be reported when using the list again) del lis1 # print(lis1) '''Modification of elements in the list''' print(lis2) # Modify the element of the specified index lis2=100 print(lis2) # Slice method to modify a list # The newly specified list will replace the elements of the specified index interval. If the interval exceeds, it will be added directly at the end # If the number of elements in the slice is inconsistent with the number of elements in the slice to be changed, it doesn't matter to replace it directly lis2[10:]=[1,2,3] print(lis2) # del can also delete the element at the specified location del lis del lis[2:4] # You can also directly empty  a section of the list to achieve the effect of deletion lis2[2:4]=
Tuples are immutable sequences, so addition and deletion are not supported. Here we only introduce their characteristics and points for attention.
Tuples are also a set of ordered sequences, which contain zero or more references to objects. They are very similar to lists, but there are many differences
Specifically, it has the following characteristics:
Tuples are immutable sequences. Only reading is supported
1. Adding element [add] is not supported
2. Deleting element [delete] is not supported
3. Modifying elements is not supported (the steps of modifying are: delete first and then add) [ modify ]
4. Two kinds of search elements are supported
a. Searching for elements according to subscripts is often called [access] element, and the time complexity is O (1)
b. Obtaining subscripts based on elements is often called [find] element, and the time complexity is O (n)
If there is only one data in the tuple, the comma after the data cannot be omitted
Parentheses of tuples can be omitted.
The declaration and traversal of Yuanzu are as follows:
# Tuple declaration 1 s=('Tom',666,'hi') print(s,type(s)) # Tuple declaration 2 p=tuple(('Tom',666,'hi')) print(p) # Empty tuple ss=() print(ss,type(ss)) # Single element tuple -- to be added, otherwise it will be directly converted to string type sss=('fuck') print(sss,type(sss)) # Parentheses of tuples can be omitted sss='fuck', print(sss,type(sss)) tp=('nabd',['123',123],'Li Si') print(tp) # The element of the corresponding position of the tuple will not change, but the content of the element of the corresponding position of the tuple can be changed tp.insert(1,666) print(tp) # Traversal of tuples for temp in s: print(temp)
String has been mentioned in the previous blog,I won't repeat it here.
5, Byte sequence
Byte sequence can be divided into variable byte array and immutable byte sequence.
To generate a byte sequence using literals, you only need to add b before the string.
You can also use bytes() or byte array () to declare byte sequences
The parameters can be passed to the iteratable object, but the members of the iteratable object should be integers between 0 and 255.
The methods of bytes or bytearray do not accept string parameters, but only parameters of the corresponding type. Otherwise, an error is reported
Byte sequences support the basic operations of sequences.
The byte sequence can be obtained by string encoding, and the string can also be obtained by decoding the character sequence
The functions used are decode() and encode(). Pay attention to the encoding and decoding rules during use.
This blog explains Python sequences. Sequences are often used in learning to use python. I hope you can master them well. If you have any good use skills, please tell the blogger in the comment area. (^_−)☆