程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Summary of list (list, array) operations in Python standard library (about 25 operations), with sample code

編輯:Python

Python List in the standard library (list) Be similar to C/C++ In the array .

Python In the extension library ndarray Objects have many operations and lists (list) Similar to , Such as slicing 、 Element access , But they are two things , Don't get confused . About ndarray Basic operation of objects , Please refer to the blog https://blog.csdn.net/wenhao_ir/article/details/124416798

The importance of arrays to programming is self-evident , So this blog post summarizes Python List in the standard library (list) The operation of .

Catalog

  • 01- Basic concepts of sequences and lists
  • 02- List creation
    • 02-1- Use square brackets directly [] establish
    • 02-2- Create with constructor
  • 03- Access to list elements
  • 04- Slice operation of list
  • 05-1 Usage method append() Add list elements
  • 05-2 Usage method extend() Appends multiple values from another sequence at once at the end of the list
  • 05-3 Usage method insert() Insert an element anywhere in the list
  • 06-1- Use del Statement to delete an element at a specified position in a list
  • 06-2- Usage method pop() Deletes the element at the specified location , And return the element value
  • 06-3- Usage method remove() Remove the element of the specified content in the list
  • 07-1 Using functions len() measurement ( return ) The length of the list
  • 07-2 Using functions max() Returns the maximum value of the element in the list
  • 07-3 Using functions min() Returns the maximum value of the element in the list
  • 08- Use the operator "+" Realize list merging
  • 09- Use the operator "*" Implement the repeated extension of the list
  • 10- Use “in” Determine whether an element is in the list
  • 11- List nesting ( Similar to multidimensional arrays - List as an element of a list )
  • 12- Use operator Methods eq() Compare two lists for equality
  • 13- Usage method count() Count the number of times an element appears in a list
  • 14- Usage method index() Find list elements
  • 15- Usage method reverse() Elements in the reverse list
  • 16- Usage method sort() Sort the list
  • 17- Usage method clear() clear list
  • 18- Usage method copy() Or method copy.append() Copy list 【 Deep copy operation 】
  • 19- Using functions tuple() Convert list to tuple

01- Basic concepts of sequences and lists

Sequence is Python The most basic data structure in .
Each value in the sequence has a corresponding position value , Call it an index , The first index is 0, The second index is 1, And so on .
The operations that can be performed by a sequence include indexing , section , Add , ride , Check members .
Besides ,Python There's a built-in way to determine the length of the sequence and determine the maximum and minimum elements .

Python Yes 6 Built in types of sequences , But the most common are lists and tuples .
Lists are the most commonly used Python data type , The data items of a list do not need to have the same type .

02- List creation

02-1- Use square brackets directly [] establish

Create a list , Just enclose the different data items separated by commas in square brackets .

list1 = ['Google', 'CSDN', 1997, 1999]
list2 = [1, 2, 3, 4, 5]
list3 = ['red', 'green', 'blue', 'yellow', 'white', 'black']

The results are shown in the following figure :

From the above results we can see that , stay Python Chinese is a word list Represents the of the list .

02-2- Create with constructor

A list is essentially an object , So you can use the constructor to create , The code is as follows :

list1 = list()
list1.append('Google')
list1.append('CSDN')
list1.append('1997')
list1.append('1999')

The operation results are as follows :

From above , Obviously the first 1 Methods 2 This method is convenient . But when you want to use member functions append() When adding elements , If you use the first method ,Pycharm This is not recommended , As shown in the figure below :

This list creation could be rewritten as a list literal.

This sentence means that the list should be created according to its original meaning . What is original meaning creation ? A list is essentially an object , Since the object , Then use the constructor to initialize and create .
The following two articles explain the reasons for this problem :
https://www.cnblogs.com/jiangxiaobo/p/11622730.html
https://zhuanlan.zhihu.com/p/222401764

03- Access to list elements

The sample code is as follows :

list1 = ['Google', 'CSDN', 1997, 1999]
print(list1[0])
print(list1[1])
print(list1[2])

The operation results are as follows :

Except from left to right , Or from right to left , The sample code is as follows :

list1 = ['Google', 'CSDN', 1997, 1999]
print(list1[-1])
print(list1[-2])
print(list1[-3])

The operation results are as follows :

04- Slice operation of list

The sample code is as follows :

list1 = ['Google', 'CSDN', 'tencent', 1997, 1999, 1998]
list2 = list1[0:4]

Be careful : The section is left closed and right open , namely [0:4] amount to [0,4)
The operation results are as follows :

You can also combine positive and negative indexes :

list1 = ['Google', 'CSDN', 'tencent', 1997, 1999, 1998]
list2 = list1[0:-2]

above list1[0:-2] To intercept 0 To the last 2 Clips of , The operation results are as follows :

05-1 Usage method append() Add list elements

Be careful : In this case, we use the constructor to create the list , Instead of using brackets to create lists , otherwise Pycharm This is not recommended , As shown in the figure below :

This list creation could be rewritten as a list literal.

This sentence means that the list should be created according to its original meaning . What is original meaning creation ? A list is essentially an object , Since the object , Then use the constructor to initialize and create .
The following two articles explain the reasons for this problem :
https://www.cnblogs.com/jiangxiaobo/p/11622730.html
https://zhuanlan.zhihu.com/p/222401764

The sample code is as follows :

list1 = list()
list1.append('Google')
list1.append('CSDN')
list1.append('1997')
list1.append('1999')

The operation results are as follows :

Pay special attention to : When using method append() When the added element itself is also a list , This is the shallow copy operation , That is, the copied list value changes , Then the value of the corresponding element in the list will also change , The sample code is as follows :

list1 = list()
list1.append('Google')
list1.append('CSDN')
list1.append('1997')
list1.append('1999')
list2 = [2010]
list1.append(list2)
list2[0] = 4444

The operation results are as follows :

If it's a deep copy , that list1 No 4 Element values should be [2010] That's right .

If you want to make a deep copy of the list , You can do this as follows :

import copy
list1 = list()
list1.append('Google')
list1.append('CSDN')
list1.append('1997')
list1.append('1999')
list2 = [2010]
list1.append(copy.deepcopy(list2))
list2[0] = 4444

The operation results are as follows :

Of course, you can also use the method copy() Realization , Namely code :

list1.append(copy.deepcopy(list2))

Can be replaced by

list1.append(list2.copy())

For general variables , The effect is a deep copy , The code is as follows :

list1 = list()
list1.append('Google')
list1.append('CSDN')
list1.append('1997')
list1.append('1999')
value1 = 2030
list1.append(value1)
value1 = 4444

The operation results are as follows :

05-2 Usage method extend() Appends multiple values from another sequence at once at the end of the list

As we can see from the above example , Method append() Is to make the appended list as a whole ( As an element ) Added to the original list , Sometimes we want to append multiple values from another sequence at the end of the list at once , This time you can use the method extend() Realization .
The sample code is as follows :

list1 = ['Google', 'CSDN', 'Taobao']
list2 = [1997, 1999, 1998]
list1.extend(list2)

The operation results are as follows :

05-3 Usage method insert() Insert an element anywhere in the list

The sample code is as follows :

list1 = ['Google', 'CSDN', 'Taobao', 1997, 1999, 1998, 1999]
list1.insert(3, 'Tecent')

The operation results are as follows :

06-1- Use del Statement to delete an element at a specified position in a list

The sample code is as follows :

list1 = ['Google', 'CSDN', 'tencent', 1997, 1999, 1998]
del list1[2]

The operation results are as follows :

From the above results , The first 2 Elements ’tencent’ Been deleted .

06-2- Usage method pop() Deletes the element at the specified location , And return the element value

Method pop() The grammar is as follows :

list.pop([index=-1])

index – Optional parameters , To remove the index value of a list element , Cannot exceed the total length of the list , The default is index=-1, Delete the last list value .
The sample code is as follows :

list1 = ['Google', 'CSDN', 'tencent', 1997, 1999, 1998]
list2 = ['Google', 'CSDN', 'tencent', 1997, 1999, 1998]
value1 = list1.pop()
value2 = list1.pop(1)

The operation results are as follows :

06-3- Usage method remove() Remove the element of the specified content in the list

The sample code is as follows :

list1 = ['Google', 'CSDN', 'tencent', 1997, 1999, 1998, 'CSDN']
list1.remove('CSDN')

The operation results are as follows :

From the above results, we can see , Method remove() What is removed is the first matching element . The above string element ’CSDN’ There are two , But only the first one was deleted .

07-1 Using functions len() measurement ( return ) The length of the list

The sample code is as follows :

len1 = len([1, 2, 3])
list1 = ['Google', 'CSDN', 'tencent', 1997, 1999, 1998]
len2 = len(list1)

The operation results are as follows :

07-2 Using functions max() Returns the maximum value of the element in the list

The sample code is as follows :

list1 = [456, 700, 200]
max1 = max(list1)

The operation results are as follows :

07-3 Using functions min() Returns the maximum value of the element in the list

The sample code is as follows :

list1 = [456, 700, 200]
min1 = min(list1)

The operation results are as follows :

08- Use the operator "+" Realize list merging

The sample code is as follows :

list1 = ['Google', 'CSDN', 'tencent', 1997, 1999, 1998]
list2 = [4, 5, 6]
list3 = list1+list2

The operation results are as follows :

09- Use the operator "*" Implement the repeated extension of the list

The sample code is as follows :

list1 = ['Google', 'CSDN', 'tencent', 1997, 1999, 1998]
list2 = [4, 5, 6]
list3 = list1*2
list4 = list2*3

The operation results are as follows :

10- Use “in” Determine whether an element is in the list

The sample code is as follows :

list1 = ['Google', 'CSDN', 'tencent', 1997, 1999, 1998]
bool1 = 'CSDN' in list1
bool2 = 'zhihu' in list1

The operation results are as follows :

11- List nesting ( Similar to multidimensional arrays - List as an element of a list )

List nesting , Essentially, a list can also be used as an element of a list .

The sample code is as follows :

list1 = [['Google', 'CSDN', 'tencent'], [1997, 1999, 1998]]
a1 = list1[0][1]
b1 = list1[1][2]

The operation results are as follows :

Be careful , For sentences :

a1 = list1[0][1]
b1 = list1[1][2]

Can not be like ndarray The object is written as follows :

a1 = list1[0, 1]
b1 = list1[1, 2]

Error will be reported at this time :

ndarray See the following blog post for details of accessing multidimensional matrix elements of :
https://blog.csdn.net/wenhao_ir/article/details/124419922

12- Use operator Methods eq() Compare two lists for equality

The sample code is as follows :

import operator
a = [1, 2]
b = [2, 3]
c = [2, 3]
bool1 = operator.eq(a, b)
bool2 = operator.eq(c, b)

The operation results are as follows :

13- Usage method count() Count the number of times an element appears in a list

The sample code is as follows :

list1 = [123, 'Google', 'CSDN', 'Taobao', 123]
count1 = list1.count(123)
count2 = list1.count('CSDN')

The operation results are as follows :

14- Usage method index() Find list elements

Method index() The grammar is as follows :

list.index(x[, start[, end]])

x-- Objects found .
start-- Optional , The starting point of the search .
end-- Optional , End of search .
The sample code is as follows :

list1 = ['Google', 'CSDN', 'Taobao', 1997, 1999, 1998, 1999]
index1 = list1.index('CSDN')
index2 = list1.index(1999)

The operation results are as follows :

In the list 1999 There are two , It can be seen that the first index is returned .

15- Usage method reverse() Elements in the reverse list

The sample code is as follows :

list1 = [1, 2, 3, 4, 5, 6, 7]
list1.reverse()

The operation results are as follows :

16- Usage method sort() Sort the list

Method sort() The grammar is as follows :

list.sort( key=None, reverse=False)

key – The value used for comparison , Optional parameters .
reverse – Sort rule ,reverse = True Descending , reverse = False Ascending ( Default ).
The sample code is as follows :

list1 = [1, 5, 3, 9, 7, 4, 2, 8, 6]
list1.sort()
list2 = [1, 5, 3, 9, 7, 4, 2, 8, 6]
list2.sort(reverse=True)

The operation results are as follows :

About the way sort() The first parameter of key Usage of , It's a long story , For details, please refer to another blog post :
https://blog.csdn.net/wenhao_ir/article/details/125406092

17- Usage method clear() clear list

The sample code is as follows :

list1 = ['Google', 'CSDN', 'Taobao', 1997, 1999, 1998, 1999]
list1.clear()

The operation results are as follows :

18- Usage method copy() Or method copy.append() Copy list 【 Deep copy operation 】

Method copy() An example of the use of :

list1 = ['Google', 'CSDN', 'Taobao', 1997, 1999, 1998, 1999]
list2 = list1.copy()
list1[0] = 'Facebook'

The operation results are as follows :

From the above code and running results, we can see , Method copy() It's a deep copy .

Method copy.append() An example of the use of :

import copy
list1 = ['Google', 'CSDN', 'Taobao', 1997, 1999, 1998, 1999]
list2 = copy.deepcopy(list1)
list1[0] = 'Facebook'

The operation results are as follows :

From the above code and running results, we can see , Method copy.append() It is also a deep copy .

19- Using functions tuple() Convert list to tuple

The sample code is as follows :

list1 = ['Google', 'Taobao', 'CSDN', 'Baidu']
tuple1 = tuple(list1)

The operation results are as follows :

Detailed operations on tuples , You can refer to my other blog post , Links are as follows :
https://blog.csdn.net/wenhao_ir/article/details/125407815

Reference material :
https://blog.csdn.net/wenhao_ir/article/details/125100220


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved