列表实战——就地改变列表——其它常见的列表方法

未匹配的标注

和字符串一样,列表有执行其它特殊操作的其它方法。比如,reverse 就地反转列表, extendpop方法在列表末尾分别插入多个项和删除一个项。还有和 sort很像并返回一个新的结果对象的内置函数 reversed,但它在2系列和3系列中都必须包裹在一个 list调用中,因为它的结果是一个按需生成结果的迭代器(更多关于迭代器请参阅后面):

>>> L = [1, 2]
>>> L.extend([3, 4, 5]) # Add many items at end (like in-place +)
>>> L
[1, 2, 3, 4, 5]
>>> L.pop() # Delete and return last item (by default: −1)
5
>>> L
[1, 2, 3, 4]
>>> L.reverse() # In-place reversal method
>>> L
[4, 3, 2, 1]
>>> list(reversed(L)) # Reversal built-in with a result (iterator)
[1, 2, 3, 4]

技术上讲,extend方法总是迭代并添加可迭代对象中的每一项,然而append只按原样添加一项而没有迭代它——在第14章将会更有意义的一个区别。就现在来说,知道 extend添加许多项,而append添加一项就足够了。在某些类型的程序中,列表的 pop 方法通常和 append一起使用来实现一个快速的后进先出(LIFO)结构。列表的末尾作为栈的顶部:

>>> L = []
>>> L.append(1) # Push onto stack
>>> L.append(2)
>>> L
[1, 2]
>>> L.pop() # Pop off stack
2
>>> L
[1]

pop方法还接收一个可选的项偏移量来被删除和被返回(默认值是在偏移量-1的最后一项)。其它的列表方法通过值移除一个项(remove),在一个偏移量处插入一个项(insert),对发生数计数(count),并搜索一个项的偏移量(index——对项的index的搜索,不要和索引操作混淆!):

>>> L = ['spam', 'eggs', 'ham']
>>> L.index('eggs') # Index of an object (search/find)
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']
>>> L.count('spam') # Number of occurrences
1

注意不像其他列表方法,count 和 index 不改变列表自身,但返回关于其内容的信息。参见其他文档源或交互地亲自实验这些调用来学习更多关于列表方法的知识。

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
讨论数量: 0
发起讨论 只看当前版本


暂无话题~