Four common data structures built into Python: list, tuple, dict, and set.
These four data structures can be used to store multiple data items, which is very important for programming, because the program not only needs to use a single variable to store data, but also needs to use multiple data structures to store large amounts of data. Lists, tuples, dictionaries and collections can meet the needs of storing large amounts of data.
List (list) and tuple (tuple) are similar, they both store elements in order, and each element has its own index, so both lists and tuples can access elements by index. The difference between the two is that tuples are unmodifiable, but lists are modifiable.
Dictionary (dict) is similar to set (set), the data they store are all out of order, and the dictionary stores data in the form of key-value
Detailed python sequence
The so-called sequence refers to a contiguous memory space that can store multiple values. These values are arranged in a certain order and can be accessed through the number (called index) where each value is located.
Regardless of whether it is a positive index value or a negative index value, any element in the sequence can be accessed.
Note that when using a negative value as the index value of each element in the column sequence, it starts from -1, not from 0.
[ root@kube list]# cat demo1.py
str="Py serialization detailed"print(str[0],"---",str[-6])print(str[5],"---",str[-1])[root@kube list]# py demo1.py
P --- y
detailed---solution
[ root@kube list]#
Sequence slice
The slicing operation is another way to access the elements in the sequence. It can access the elements in a certain range. Through the slicing operation, a new sequence can be generated.
The syntax format of the sequence to implement the slice operation is as follows:
sname[start : end : step]
Among them, the meaning of each parameter is:
sname: indicates the name of the sequence;
start: Indicates the starting index position of the slice (including this position), this parameter can also be left unspecified, it will default to 0, that is, slice from the beginning of the sequence;
end: indicates the end index position of the slice (not including this position), if not specified, the default is the length of the sequence;
step: In the slicing process, the element is taken once every several storage locations (including the current position), that is to say, if the value of step is greater than 1, then the element will be taken "jumping" when slicing to sequence the elements . If the value of step is omitted, the last colon can be omitted.
[ root@kube list]# cat demo2.py
str="py sequence slice"print(str[:0]) #end is 0 means the end index position but does not include this position,So empty
print(str[:1])print(str[:2])print(str[1:2])
num="123456789"print(num[1:5:2]) #at 1-Take a value every two digits in the interval of 5
[ root@kube list]# py demo2.py
p
py
y
24[ root@kube list]#
Sequence addition
In Python, two sequences of the same type are supported using the "+" operator to do the addition operation, which will connect the two sequences, but will not remove duplicate elements.
The "same type" mentioned here means that the sequences on both sides of the "+" operator are either sequence types, tuple types, or strings.
root@kube list]# cat demo3.py
print("Hello there"+"I'm good"+"dajiahao")[root@kube list]# py demo3.py
Hello my good dajiahao
[ root@kube list]#
Sequence multiplication
In Python, multiplying a sequence by the number n will generate a new sequence whose content is the result of the original sequence being repeated n times
[ root@kube list]# cat demo3.py
str="Hello there"+"I'm good"+"dajiahao"print(str*3)[root@kube list]# py demo3.py
Hello my good dajiahao hello my good dajiahao hello my good dajiahao
[ root@kube list]#
Check if the element is included in the sequence
In Python, you can use the in keyword to check whether an element is a member of a sequence. The syntax format is:
value in sequence
The usage is the same as the in keyword, but the function is exactly the opposite. There is also the not in keyword, which checks whether an element is not included in the specified sequence.
value not in sequence
[ root@kube list]# cat demo4.py
# coding:utf-8
str="test.com.cn"print('e'in str)print('e' not in str)[root@kube list]# py demo4.py
True
False
[ root@kube list]#
Built-in functions related to sequences
Python provides several built-in functions (shown in Table 3), which can be used to implement some common operations related to sequences
Table 3 Sequence-related built-in functions
Function | function |
---|---|
len() | Calculate the length of the sequence, that is, return how many elements are contained in the sequence. |
max() | Find the largest element in the sequence. Note that when using the sum() function on a sequence, all addition operations must be numbers, not characters or strings, otherwise the function will throw an exception, because the interpreter cannot determine whether to do the concatenation operation (+ operator You can connect two sequences), or do addition operations. |
min() | Find the smallest element in the sequence. |
list() | Convert sequence to list |
str() | Convert the sequence to a string. |
sum() | Calculate the sum of the elements. |
sorted() | sort the elements. |
reversed() | Reverse the elements in the sequence. |
enumerate() | Combine sequences into an index sequence, which is mostly used in for loops. |
[ root@kube list]# cat demo5.py
str="test.com.cn"print(max(str))print(min(str))print(len(str))print(list(str))[root@kube list]# py demo5.py
t
.11[' t','e','s','t','.','c','o','m','.','c','n'][root@kube list]#
python list list
There are no arrays in Python, but more powerful lists have been added. If you think of an array as a container, then a Python list is a warehouse of a factory.
From a formal point of view, the list will put all elements in a pair of square brackets [], and adjacent elements are separated by commas. In the format, element1~elementn represent the elements in the list, and the number is unlimited, as long as it is Python The supported data types are fine. As follows
[ element1,element2,element3,...,elementn]
[ root@kube list]# cat demo6.py
lt=['c.test.com',1,[2,3],2.34,'aa']print(lt)print(type(lt))[root@kube list]# py demo6.py
[' c.test.com',1,[2,3],2.34,'aa']<class'list'[root@kube list]#
Create list
[ root@kube list]# cat demo7.py
lt=[1,'x.test.com',[2,3]] # =Number assignment use[]Enclose
str="1234test"print(type(lt))print(type(str))
lt2=list(str) #Use list()Function conversion
print(lt2)print(type(lt2))[root@kube list]# py demo7.py
< class'list'<class'str'['1','2','3','4','t','e','s','t']<class'list'[root@kube list]#
python access and delete lists
[ root@kube list]# cat demo8.py
vol=[1,'test.com',[3,4,5],44,'fff','ee']print(vol[:1])print(vol[:2])print(vol[2:4])
del vol
print(vol)[root@kube list]# py demo8.py
[1][1,' test.com'][[3,4,5],44]Traceback(most recent call last):
File "demo8.py", line 6,in<module
print(vol)
NameError: name 'vol' is not defined
[ root@kube list]#
Three ways to add elements to python list list
The append() method is used to append elements to the end of the list. The syntax of this method is as follows:
listname.append(obj)
Of course, if you want to not treat the appended list or tuple as a whole, but only append the elements in the list, you can use the extend() method provided by the list. The syntax format of extend() method is as follows:
listname.extend(obj)
If you want to add elements in the middle of the list, you can use the insert() method of the list. The syntax format of this method is:
listname.insert(index , obj)
Among them, the index parameter refers to the index value at which the element is inserted into the specified position in the list.
Use the insert() method to insert an element into the list, just like the append() method. Regardless of whether the inserted object is a list or a tuple, it will only be regarded as an element as a whole.
[ root@kube list]# cat demo9.py
a_list=['test.com.cn',2,[2,'a']]
a_list.append('b')print(a_list)
a_list.extend([9,8,7])print(a_list)
a_list.insert(4,'MM')print(a_list)[root@kube list]# py demo9.py
[' test.com.cn',2,[2,'a'],'b']['test.com.cn',2,[2,'a'],'b',9,8,7]['test.com.cn',2,[2,'a'],'b','MM',9,8,7][root@kube list]#
Three ways to delete elements in python list
Deleting elements from the list is mainly divided into the following 3 application scenarios:
1 Delete according to the index value of the location of the target element, you can use the del statement;
2 To delete according to the value of the element, use the remove() method provided by the list (list type);
3 To delete all elements in the list, use the clear() method provided by the list (list type).
python list modify elements
The elements of the list are equivalent to variables, so the program can assign values to the elements of the list, so that you can modify the elements of the list
slice can also be used
[ root@kube list]# cat demo11.py
a_list=list(range(0,10)) #list()Convert function to list
print(a_list)
a_list[2]='a' #Replace the value of sequence 2
print(a_list)
a_list[-1]='ffff' #The replacement sequence is-1 value
print(a_list)
a_list[3:4]=['s','d'] #Replace shard 3-Value of 4
print(a_list)
a_list[4:6]=[] #Put 4-Replace the value of 6 with empty
print(a_list)
a_list[1:3]='test' #When using slice syntax to assign a value to a list, you cannot use a single value; if you use string assignment, Python will automatically treat the string as a sequence, where each character is an element.
print(a_list)
a_list[2:6:2]=['MM','NN'] #When assigning values using slice syntax, you can also specify the step parameter. But if the step parameter is specified, the number of list elements assigned is required to be equal to the number of list elements replaced
print(a_list)[root@kube list]# py demo11.py
[0,1,2,3,4,5,6,7,8,9][0,1,' a',3,4,5,6,7,8,9][0,1,'a',3,4,5,6,7,8,'ffff'][0,1,'a','s','d',4,5,6,7,8,'ffff'][0,1,'a','s',5,6,7,8,'ffff'][0,'t','e','s','t','s',5,6,7,8,'ffff'][0,'t','MM','s','NN','s',5,6,7,8,'ffff'][root@kube list]#
Python list common methods
In addition to the previous methods of adding elements, deleting elements, and modifying elements, the list also contains some commonly used methods.
count() method, this method is used to count the number of occurrences of an element in the list
listname.count(obj)
The index() method is used to locate the position where an element appears in the list (that is, the index). If the element does not appear, a ValueError will be raised. The basic syntax format of this method is
listname.index(obj,start,end)
Unlike the count() method, the index() method can also be passed in start and end parameters to search for elements within the specified range of the list.
The pop() method will remove the element at the specified index in the list. If not specified, the last element in the list will be removed by default. The basic syntax format of this method is:
listname.pop(index)
The reverse() method stores all elements in the list in reverse. The basic syntax format of this method is:
listname.reverse()
The sort() method is used to sort the list elements, and the order of the elements in the original list will only change after sorting. The syntax format of the sort() method is as follows:
listname.sort(key=None, reserse=False)
As you can see, unlike other methods, there are two more parameters in this method. Their functions are:
The key parameter is used to specify to extract a key for comparison from each element. For example, when using this method, setting key=str.lower means that letter case is not distinguished when sorting.
The reverse parameter is used to set whether the sorting needs to be reversed. The default False means sorting from smallest to largest; if this parameter is set to True, it will be sorted from largest to smallest.
The following code demonstrates an example of using a list as a "stack":
stack =[]
# "Push" 3 elements into the stack
stack.append("fkit")
stack.append("crazyit")
stack.append("Charlie")print(stack) # ['fkit','crazyit','Charlie']
# First pop: The last element pushed onto the stack is removed from the stack
print(stack.pop())print(stack) # ['fkit','crazyit']
# Pop again
print(stack.pop())print(stack) # ['fkit']
python range quickly initialize a list of numbers
The ython range() function can easily generate a series of numbers. For example, you can use range() to print a series of numbers as follows:
[ root@kube list]# cat demo14.py
# coding:utf-8
seq=[]for i inrange(1,4): #Find 1-Product of 3
vol=i**2
seq.append(vol)print(seq)print('----------------------------')print(type([1,2,3,4])) #Type conversion of range
print(type(range(1,5)))[root@kube list]# py demo14.py
[1,4,9]- - - - - - - - - - - - - - - - - - - - - - - - - - - - < class'list'<class'range'[root@kube list]#
python list list implementation stack and queue
Queue and stack are two data structures. Variables are stored in a fixed order inside. The difference between the two lies in the order of data access:
In the queue, the data stored first is taken out first, that is, "first in, first out".
The stack is that the data stored last is taken out first, that is, "last in, first out".
Considering that the storage of the list type data itself is ordered, and the internal elements can be of different types, it is very suitable for the implementation of queues and stacks. This section will demonstrate how to use list type variables to implement queues and stacks.
python list list implementation
The way to use the list to simulate the queue function is to define a list variable, use the insert() method when storing data, and set its first parameter to 0, which means that data is inserted from the front every time; when reading data , Use the pop() method to pop the last element of the queue.
[ root@kube list]# cat demo15.py
# coding:utf-8
# Define an empty list as a queue
queue =[]
# Insert an element into the list
queue.insert(0,"one")
queue.insert(0,"two")
queue.insert(0,"three")print(queue)print('Take the first element:',queue.pop()) #pop()Take the last digit of the queue by default
print('Take the second element:',queue.pop())print('Take the third element:',queue.pop())[root@kube list]# py demo15.py
[' three','two','one']
Take the first element: one
Take the second element: two
Take the third element: three
[ root@kube list]#
Python implementation stack
The way to use the list to simulate the stack function is to use the append() method to store data; use the pop() method to read data. When the append() method saves data to the list, it adds the data at the end each time, which is exactly the opposite of the insert() method in the previous program.
[ root@kube list]# cat demo16.py
# coding:utf-8
# Define a list as the stack
stack =[]
stack.append('one')
stack.append('two')
stack.append('three')print(stack)print('Take the first element:',stack.pop())print('Take the second element:',stack.pop())print('Take the third element:',stack.pop())[root@kube list]# py demo16.py
[' one','two','three']
Take the first element: three
Take the second element: two
Take the third element: one
[ root@kube list]#
The collections module implements stacks and queues
queueAndStack =deque()
queueAndStack.append(1)
queueAndStack.append(2)
queueAndStack.append("hello")print(list(queueAndStack))
# Realize the queue function, take an element from the queue, according to the first-in first-out principle, here should output 1print(queueAndStack.popleft())
# Realize the stack function, take an element from the stack, according to the last in first out principle, here should output hello
print(queueAndStack.pop())
# Print list again
print(list(queueAndStack))
The above is an in-depth understanding of the details of the python list (LIST). For more information about Python (list), please pay attention to other related articles on ZaLou.Cn!
Recommended Posts