跟老齐学Python之有容乃大的list(2)

2019-10-05 19:24:10王冬梅

list.count(x)
Return the number of times x appears in the list.
一定要不断实验,才能理解文档中精炼的表达。

>>> la = [1,2,1,1,3]
>>> la.count(1)
3
>>> la.append('a')
>>> la.append('a')
>>> la
[1, 2, 1, 1, 3, 'a', 'a']
>>> la.count('a')
2
>>> la.count(2)
1
>>> la.count(5)   #NOTE:la中没有5,但是如果用这种方法找,不报错,返回的是数字0
0

元素在list中的位置

《有容乃大的list(1)》中已经提到,可以将list中的元素,从左向右依次从0开始编号,建立索引(如果从右向左,就从-1开始依次编号),通过索引能够提取出某个元素,或者某几个元素。就是如这样做:

>>> la
[1, 2, 3, 'a', 'b', 'c', 'qiwsir', 'python']
>>> la[2]
3
>>> la[2:5]
[3, 'a', 'b']
>>> la[:7]
[1, 2, 3, 'a', 'b', 'c', 'qiwsir']

如果考虑反过来的情况,能不能通过某个元素,找到它在list中的编号呢?

看官的需要就是python的方向,你想到,python就做到。

>>> la
[1, 2, 3, 'a', 'b', 'c', 'qiwsir', 'python']
>>> la.index(3)
2
>>> la.index('a')
3
>>> la.index(1)
0
>>> la.index('qi')   #如果不存在,就报错
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 ValueError: 'qi' is not in list
>>> la.index('qiwsir')
6

list.index(x),x是list中的一个元素,这样就能够检索到该元素在list中的位置了。这才是真正的索引,注意那个英文单词index。

依然是上一条官方解释:

list.index(x)
Return the index in the list of the first item whose value is x. It is an error if there is no such item.
是不是说的非常清楚明白了?

先到这里,下讲还继续有容乃大的list.