This series of notes for learning Python for yourself, if there are errors, please correct me
List features
Sequence is a data storage method used to store a series of data. In memory, a sequence is a block used to store multiple valuescontinuousMemory space. For example, a total of integer sequence [10,20,30,40] can be schematically represented as follows:
Since everything in python3 is an object, it is actually stored in the following way in memory:
a=[10,20,30,40]
From the figure, it can be seen that the address of the integer object is stored in the sequence, not the value of the integer object. Commonly used sequence structures in python are: string list meta ancestor dictionary collection.
Introduction to List
List: used to store any number and type of data collection
The list has a built-in variable sequence, which is an orderly continuous memory space containing multiple elements. Standard syntax format for list definition:
a=[10,20,30,40]
Among them, 10 20 30 40 are called: elements of list a
The elements in the list can be different and of any type. such as:
a=[10,20,‘abc’,True]
Common methods of list objects:
method | Point | description |
---|---|---|
list.append(x) | Add elements | Add element x to the end of the list |
list.extend(aLIst) | Add elements | Add all elements of the list aLIst to the end of the list |
list.insert(index,x) | Add elements | Insert element x at the specified position index in the list |
list.remove(x) | Delete element | Delete the first occurrence of the specified element x in the list |
list.pop(x) | Delete element | Delete and return the element at the specified position index of list |
list.pop([index]) | Delete element | Delete and return the element at the specified position index of the list, the default is the last element |
list.clear() | Delete all elements | Delete all elements of the list, not delete the list object |
list.index(x) | Access element | Returns the index position of the first x, throws an exception if there is no x element |
list.count(x) | count | Returns the number of times the specified element x appears in the list |
flax (list) | List length | Returns the number of elements in the list |
list.reverse() | Flip list | All elements are flipped in place |
list.sort() | Sort | Sort all elements in place |
list.copy() | Shallow copy | Return a shallow copy of the list object |
Python's list size is variable, increase or decrease as needed
Both strings and lists are sequence types, a string is aCharacter sequence, A list isAny elementthe sequence of.
List creation
The creation of the basic syntax []
a = [10,20,'slp','sx']
a=[] #创建一个空的列表对象
list() create
Use list() to convert any iterable data into a list
a =list()# 创建一个空的列表对象
a = list(range(10))
a = list('slp,sx')
range() creates a list of integers
range() can help us create a list of integers very conveniently: range([start],end,[step])
- start: optional starting number default 0
- end: required ending number
- step: Optional means that the step size is 1 by default
Range() in python3 returns a range object, not a list, we need to convert it into a list object through the list method.
Comprehensively generated list
Use list comprehension can be very convenient to create data, often used in development. However, due to the for loop and if statement
a = [x*2 for x in range(5)] #循环创建多个元素
a = [x*2 for x in range(100) if x%9==0] #通过if过滤元素
Add and delete list elements
When the list adds and deletes elements, the list will automatically perform memory management, which greatly reduces the burden on the programmer. However, this feature involves a large number of movement of list elements, which is inefficient. Unless graduated, we generally only add elements to the end of the list, which will greatly increase the efficiency of the list.
append() method
Modifying the list object in place is the fastest way to add new elements to the end of the list. Recommended Use
a = [20,40]
a.append(80)
+ Operator operation
It is not really adding elements at the end, but creating a new list object; copy the elements of the original list and the elements of the new list to the new list object in turn. In this way, a large number of copy operations are involved, and it is not recommended to operate a large number of elements.
a = [20,40]
id(a) #46016027
a = a+[50]
id(a)# 46015432
From the above, the address of a has changed, that is, a new list object is created.
extend() method
Adding all the elements of the target list to the end of this list is an in-situ operation and does not create a new list object
a = [20,40]
a.extend([50,60])
insert() insert element
Use the insert() method to insert the specified element into any specified position of the list object. This will move all the elements behind the insertion position, which will affect the processing speed. When a large number of elements are involved, try to avoid using them. Similar to this kind of movement function there is remove() pop() del() They will also move the elements behind the operating position when they delete non-tail elements.
Multiplication extension
Use multiplication to expand the list to generate a new list. The new list element is multiple repetitions of the original list element.
Also suitable for multiplication operations: string ancestor.
del delete
Delete the element at the specified position of the list (the underlying principle is still a copy of the array)
a = [10,20,30]
del a[1] #删除第一个元素,下标是从0开始的
pop() method
pop() deletes and returns the element at the specified position, if no position is specified, the last element of the list is operated by default
a = [10,20,30]
a.pop() #30
remove()
Delete the specified element that appears for the first time, and throw an exception if the element does not exist
a=[10,20,10,30]
a.remove(10) #[20,10,30]
Access and count of list elements
Direct access to elements through index
We can directly access the element through the index. The index range is in the range of [0, list length-1]. If it exceeds this range, an exception will be thrown.
index() Get the index of the first occurrence of the specified element in the list
index() can get the index position of the first occurrence of the specified element, the syntax is index(value,[start,[end]]) where start and end specify the search range
count() Get the number of times the specified element appears in the list
count() can return the number of times the specified element appears in the list
a = [10,20,10,30]
a.count(10) #2
len() returns the length of the list
len() returns the length of the list, which is the number of elements
Membership judgment
To determine whether there is a specified element in the list, we can use the count() method. If it returns 0, it means it does not exist. If it is greater than 0, it means it exists, but generally we will use the more concise in keyword to judge, and return True or False directly
a = [10,20,40]
10 in a #True
Slice operation
Slicing is a python sequence and its important operation, suitable for lists, meta-ancestors, strings, etc.
The format of the slice is as follows:
[Start offset start and end offset end [:step length]]
The typical operation is as follows (when the parameter is positive):
Operation and instructions | Example | result |
---|---|---|
[:] Extract the entire list | [10,20,30] [:] | [10,20,30] |
[start: from the start index to the end] | [10,20,30] [1:] | [20,30] |
[:end] From the beginning to end-1 | [10,20,30] [:2] | [10,20] |
[start:end]From start to end-1 | [10,20,30,40] [1:3] | [20,30] |
[start: end: step] Extract from start to end-1, the step length is step | [10,20,30,40,50,60,60] [1:6:2] | [20,40,60] |
Other operations (three quantities are negative):
Example | Description | result |
---|---|---|
[10,20,30,40,50,60,70] [-3:] | Last three | [50,60,70] |
[10,20,30,40,50,60,70] [-5:-3] | The fifth from the bottom to the third from the bottom (the header does not include the tail) | [30,40] |
[10,20,30,40,50,60,70] [::-1] | The step size is negative, and the extraction is reversed from right to left | [70,60,50,40,30,20,10] |
During the slicing operation, the start offset and end offset are not in the range of [0, string length-1], andNo error, The start less than 0 will be regarded as 0, the end greater than the length -1 will be regarded as -1
List traversal
for i in listObj:
doSomething()
Copy all elements of the list to the new list object
Does the following code implement copying of list elements?
list1 = [30,40,50]
list2 = list1
Just point list2 to the list object, that is, list2 and list1 have the same address value. The list element itself is not copied.
List sort
Modify the original list, do not create the sorting of the new list
a = [20,10,30,40]
id(a)
a.sort() #默认是升序
a.sort(reerse=True) #降序排列
random.shuffle(a) #打乱顺序
Sorting of new lists
We can also sort by == built-in function sorted()==, this method returns a new list
a = [20,10,30,40]
id(a)
a = sorted(a) # 内置函数 会生成新的列表,所以下方id函数的返回值会变掉
id(a)
reversed() returns iterator
The built-in reversed() also supports reversed sorting. Unlike the reversed() method of the list object, the built-in reversed() does not modify the original list, but returns an iterator object sorted in reversed order.
a = [20,10,30,40]
c = reversed(a)
list(c) #C是一个迭代器对象,需要转换一下 迭代器只能用一次 转换一次之后就不能再用了
List built-in other functions related summary
max and min
Returns the maximum and minimum values in the list
sum
Perform a sum operation on all elements of a numeric list, and an error will be reported for a non-numeric list operation
Multidimensional list
Two-dimensional list
One-dimensional lists can help us store one-dimensional. Linear data
Two-dimensional lists can help us store two-dimensional, tabular data
a = [
['高小一',18,30000,'北京'],
['高小二',19,40000,'上海'],
['高小五',20,1000,'深圳']
]
Memory structure diagram:
Search [Zixin] on WeChat or scan the QR code below to make friends and make progress together. The article is continuously updated. At present, I am organizing the study notes of Python hundred battles, and I look forward to more updates in the future.