Python list of commonly used methods and summary

List Brief

List: for storing any number of any type of data set.
Variable sequence listing is built, ordered contiguous memory space comprises a plurality of elements. The list defines the standard syntax:

a = [10,20,30,40]

Among them, 10, 20, these are called: a list of elements.
Elements in the list may be different, may be any type. such as:

a = [10,20,'abc',True]

List of objects commonly used methods are summarized below, to facilitate learning and reference.

method Points description
list.insert(index,x) Add elements Insert the element x in the list at the specified location index list
list.append(x) End of the list of elements increases Will be added to the list of elements x tail list
list.extend(aList) A list of all the elements to the end of the list B The list alist of all elements of the tail to the list list
list.remove(x) Removing elements Delete the first occurrence of the specified element in x in list
list.pop([index]) Removing elements Removes and returns the list until the specified element at index list, the default is the last element
list.clear() Delete all of the elements Delete a list of all the elements, not to delete the list of objects
list.index(x) Accessing element Returns the index position x, x element throws an exception if there
list.count(x) count Returns the number of times specified element x appears in the list in list
len (list) List Length Returns the number of elements in the list contains
list.reverse() Flip list Flip all the elements in place
list.sort() Sequence Sort all the elements in place
list.copy() Shallow copy Returns a list of objects shallow copy
list.deepcopy() Deep copy Returns a list of objects deep copy

Strings and lists are sequences of type, a string is a sequence of characters, a list is a sequence of any element. I have
many ways to learn a string of earlier, in the list has a similar usage is almost identical.

Create a list of

The basic syntax [] to create

>>> a = [10,20,'gaoqi','sxt']
>>> a = [] #创建一个空的列表对象

list () to create

Use list () may be any data may be converted into a list of iterations.

>>> a = list() #创建一个空的列表对象
>>> a = list(range(10))
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a = list("gaoqi,sxt")
>>> a
['g', 'a', 'o', 'q', 'i', ',', 's', 'x', 't']

range () to create a list of integers

range () can help us to very easily create a list of integers, which is extremely useful in development. Syntax is:
Range ([Start,] End [, STEP])
Start parameters: optional, represent the initial numbers. The default is 0
End parameters: Required to indicate the end of the number.
step parameters: Alternatively, represents the step size of a default
in the range to python3 () returns a target range, instead of a list. We need to pass list () method
is converted into a list of objects.
A typical example is as follows:

>>> list(range(3,15,2))
[3, 5, 7, 9, 11, 13]
>>> list(range(15,3,-1))
[15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4]
>>> list(range(3,-10,-1))

[3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9]

Derivations generate a list (a brief account, with emphasis on speaking after the for loop)

It can be very easy to create a list using list comprehensions, often used in development. However, as it relates to the for loop
and if statements. In this case, make only a basic introduction. In the back of our control statements, we will explain in detail the list comprehensions more details.

>>> a = [x*2 for x in range(5)] #循环创建多个元素
>>> a
[0, 2, 4, 6, 8]
>>> a = [x*2 for x in range(100) if x%9==0] #通过 if 过滤元素
>>> a
[0, 18, 36, 54, 72, 90, 108, 126, 144, 162, 180, 198]

Add list of elements

When the add and delete elements in the list, the list will automatically memory management, greatly reducing the burden on the programmer. But
a large number of mobile characteristic involves a list of elements, less efficient. Unless necessary, we generally only add elements to the end of the list
or remove elements, which will greatly enhance the operational efficiency of the list.

append () method

Modify the list of objects in situ, it is the real end of the list to add new elements, the fastest, recommended.

>>> a = [20,40]
>>> a.append(80)
>>> a
[20, 40, 80]

+ Operator operation

Not really the tail to add elements, but to create a new list of objects; elements of the original elements of the list and the new list in turn
copied to the new object list. In this way, it will involve a lot of copy operations, to operate a large number of elements is not recommended.

>>> a = [20,40]
>>> id(a)
46016072
>>> a = a+[50]
>>> id(a)
46015432

With the above test, we found the address of a variable has changed. That is, create a new list object.

extend () method

Add all the elements of this target list to the tail of the list, are in situ operation, not create a new list object.

>>> a = [20,40]
>>> id(a)
46016072
>>> a.extend([50,60])
>>> id(a)
46016072

insert () insert elements

Use insert () method may be inserted into any specified element to develop a position of the object list. This will make the insertion position of the
surface of all the moving elements, can affect processing speed. Involving a large number of elements, try to avoid using. Similar occurrence of such
movement also functions: remove (), pop () , del (), which will occur after the operative position when the trailing elements deleting non-
moving surface element.

>>> a = [10,20,30]
>>> a.insert(2,100)
>>> a
[10, 20, 100, 30]

Multiplication Extended

Use multiplication expanded list, generate a new list, the original list of repeated elements of a new list element.

>>> a = ['sxt',100]
>>> b = a*3
>>> a
['sxt', 100]
>>> b
['sxt', 100, 'sxt', 100, 'sxt', 100]

Suitable for multiplication operation, as well as: string, a tuple. E.g:

>>> c = 'sxt'
>>> d = c*3
>>> c
'sxt'
>>> d
'sxtsxtsxt'

Delete list elements

del Delete

To delete a list element at the location.

>>> a = [100,200,888,300,400]
>>> del a[1]
>>> a
[100,200,300,400]

GVuR9e.png

pop () method

pop () Removes and returns the specified position of the element, if the location is not specified, the default action list last element.

>>> a = [10,20,30,40,50]
>>> a.pop()
50
>>> a
[10, 20, 30, 40]
>>> a.pop(1)
20
>>> a
[10, 30, 40]

remove () method

Delete the first occurrence of the specified element, if there is that element throws an exception.

>>> a = [10,20,30,40,50,20,30,20,30]
>>> a.remove(20)
>>> a
[10, 30, 40, 50, 20, 30, 20, 30]
>>> a.remove(100)
Traceback (most recent call last):
File "<pyshell#208>", line 1, in <module>
a.remove(100)
ValueError: list.remove(x): x not in list

Access count and list elements

Direct access via an index element

We can directly access the elements by index. Index interval [0, length of the list -1] range. Outside this range the
exception is thrown.

>>> a = [10,20,30,40,50,20,30,20,30]
>>> a[2]
30
>>> a[10]
Traceback (most recent call last):
File "<pyshell#211>", line 1, in <module>
a[10]
IndexError: list index out of range

index () to get the index of the specified element in the list for the first time

index () can get the index position of the first occurrence of the specified element. The syntax is: index (value, [start, [end]]). Which,
Start and end specify the scope of the search.

>>> a = [10,20,30,40,50,20,30,20,30]
>>> a.index(20)
1
>>> a.index(20,3)
5
>>> a.index(20,3) #从索引位置 3 开始往后搜索的第一个 20
5
>>> a.index(30,5,7) #从索引位置 5 到 7 这个区间,第一次出现 30 元素的位置
6

count () to obtain the specified number of elements that appear in the list

count () may return the specified number of elements that appear in the list.

>>> a = [10,20,30,40,50,20,30,20,30]
>>> a.count(20)
3

len () returns a list of length

len () returns the length of the list, i.e. the number of elements included in the list.

>>> a = [10,20,30]
>>> len(a)
3

Membership judgment

Determining whether the specified element from the list, we can use the count () method, returns 0 indicates absence, returns
more than 0 indicates the presence. However, we typically use more concise in keywords to determine, direct return True
or False.

>>> a = [10,20,30,40,50,20,30,20,30]
>>> 20 in a
True
>>> 100 not in a
True
>>> 30 not in a
False

Slicing

As we learn in front of the string, the string studied slicing operation, similar to slicing and a list of strings.
Python and the slice is a sequence of operations is important for a list of tuples, string and the like. Slice format is as follows:
slice slice operation allows us to quickly extract a sub-list or modify. Standard format is:
[start offset start: Ending offset End [: step STEP]]
NOTE: When omitting step may be omitted by the way the second colon

Typical operation (an amount of three positive number) as follows:

Operating instructions and Examples result
[:] To extract the entire list [10,20,30][:] [10,20,30]
[Start:] start from the beginning to the end of the index [10,20,30][1:] [20,30]
[: End] from the beginning know 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] extracted from start to end-1, step a step [10,20,30,40,50,60,70][1:6:2] [20, 40, 60]

Other operations (three negative amount) of the case:

Examples Explanation result
[10,20,30,40,50,60,70][-3:] Three reciprocal [50,60,70]
10,20,30,40,50,60,70][-5:-3] The fifth countdown to the antepenultimate (no header trailer) [30,40]
[10,20,30,40,50,60,70][::-1] Step is negative, the right-to-left reverse extract [70, 60, 50, 40, 30, 20, 10]

When the slicing operation, the start offset and end offset is not [0 string length - 1] this range, no error will be. The starting
offset is less than 0 as 0 will terminate offset is greater than the "length -1" will be treated as the "length -1." E.g:

>>> [10,20,30,40][1:30]
[20, 30, 40]

We found that normal output results, there is no error.

Through the list of

for obj in listObj:
	print(obj)

Copy all of the elements of the list to a new list of objects

The following code implements a list of elements to copy it?

list1 = [30,40,50]
list2 = list1

But list2 will also point to the list of objects, that is to say list1 and list2 holds address values are the same, the list of objects of this
body element and not copied.
We can by a simple method to achieve copy the contents of the list elements:

list1 = [30,40,50]
list2 = [] + list1

Note: Learning copy module, using a shallow copy or a deep copy realize our copy operation.

List sorted

Modify the original list, do not build the sort the new list

>>> a = [20,10,30,40]
>>> id(a)
46017416
>>> a.sort() #默认是升序排列
>>> a
[10, 20, 30, 40]
>>> a = [10,20,30,40]
>>> a.sort(reverse=True) #降序排列
>>> a
[40, 30, 20, 10]
>>> import random
>>> random.shuffle(a) #打乱顺序
>>> a
[20, 40, 30, 10]

Built ordering new list

We can also sort through the built-in function sorted (), this method returns a new list, do not modify the original list.

>>> a = [20,10,30,40]
>>> id(a)
46016008
>>> a = sorted(a) #默认升序
>>> a
[10, 20, 30, 40]
>>> id(a)
45907848
>>> a = [20,10,30,40]
>>> id(a)
45840584
>>> b = sorted(a)
>>> b
[10, 20, 30, 40]
>>> id(a)
45840584
>>> id(b)
46016072
>>> c = sorted(a,reverse=True) #降序
>>> c
[40, 30, 20, 10]

By the above operation, we can see, the resulting list of objects b and c are completely new object list.

reversed () returns an iterator

Built-in function reversed () also supports reverse order, with a list of objects reverse () method is different, built-in function
reversed () does not make any changes to the original list, but return an iterator object in reverse order.

>>> a = [20,10,30,40]
>>> c = reversed(a)
>>> c
<list_reverseiterator object at 0x0000000002BCCEB8>
>>> list(c)
[40, 30, 10, 20]
>>> list(c)
[]

Our findings suggest that the printout is c: list_reverseiterator. That is an iteration object. At the same time, we use the
list(c)output, it found only once. The first output element, the second is empty. That is because iteration object
the first time has traversed over, the second can not be used

List of other built-in functions related summary

max and min

It is used to return the list of maximum and minimum values.

[40, 30, 20, 10]
>>> a = [3,10,20,15,9]
>>> max(a)
20
>>> min(a)
3

sum

All elements in the list of numeric summing operation is performed, the list of non-numerical computation will be given.

>>> a = [3,10,20,15,9]
>>> sum(a)
57

Reproduced in: https://blog.csdn.net/weixin_43158056/article/details/92798505

Guess you like

Origin www.cnblogs.com/x1you/p/12592358.html