python系列教程第105讲

79 阅读1分钟

朋友们,如需转载请标明出处:blog.csdn.net/jiangjunsho…

声明:在人工智能技术教学期间,不少学生向我提一些python相关的问题,所以为了让同学们掌握更多扩展知识更好地理解AI技术,我让助理负责分享这套python系列教程,希望能帮到大家!由于这套python教程不是由我所写,所以不如我的AI技术教学风趣幽默,学起来比较枯燥;但它的知识点还是讲到位的了,也值得阅读!PS:看不懂本篇文章的同学请先看前面的文章,循序渐进每天学一点就不会觉得难了!

列表还有其他方法可执行特定的操作。例如,reverse可原地反转列表,extend和pop方法分别能够在末端插入多个元素、删除一个元素:

>>> L = [1,2]

>>> L.extend([3,4,5])    # Add many items at end

>>> L

[1,2,3,4,5]

>>> L.pop()              # Delete and return last item

5

>>> L

[1,2,3,4]

>>> L.reverse()          # In-place reversal method

>>> L

[4,3,2,1]

>>> listreversed(L))    # Reversal built-in with a result

[1,2,3,4]

在某些情况下,往往会把列表的pop方法和append方法联用,来实现快速的后进先出(LIFO,last-in-first-out)堆栈结构。列表的末端作为堆栈的顶端:

>>> L = []

>>> L.append(1# Push onto stack

>>> L.append(2>>> L

[1,2]

>>> L.pop()            # Pop off stack

2

>>> L

[1]

列表还可以通过remove方法删除某元素,用insert方法插入元素,用index方法查找某元素的偏移等:

>>> L = ['spam','eggs','ham']

>>> L.index('eggs'# Index of an object

1

>>> L.insert(1,'toast'# Insert at position

>>> L

['spam','toast','eggs','ham']

>>> L.remove('eggs'# Delete by value

>>> L

['spam','toast','ham']

>>> L.pop(1# Delete by position

'toast'

>>> L

['spam','ham']