列表_元素的访问—元素出现的次数统计_成员资格判断

列表元素访问和计数

通过索引直接访问元素

我们可以通过索引直接访问元素。索引的区间在[0,列表长度-1]这个范围。超出这个方位则会抛出异常。

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

index()获得指定元素在列表中首次出现的索引

index()可以获取指定元素首次出现的索引位置。语法:index(value,start,end),其中star和end指定了搜索范围。

>>> a
[10, 20, 30, 40, 50, 20, 30, 20, 30]
>>> a.index(20)
1
>>> a.index(20,3)   # 从索引位置3开始往后搜索第一个20
5

>>> a.index(30,5,7)  # 从索引位置5到7这个区间,搜索第一次出现30元素的位置
6

count() 获得指定元素在列表中出现的次数

count()可以返回指定元素在列表中出现的次数。

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

len()返回列表长度

len()返回列表长度,即列表中包含元素的个数。

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

成员资格判断

判断列表中是否存在指定元素,我们使用count()方法,返回0则表示不存在,返回大于0则表示存在。但是,我们一般会使用更加简洁的in关键字来判断,直接返回True或False

>>> a = [10, 20, 30, 40, 50, 20, 30, 20, 30]
>>> 100 in a
False
>>> 30 in a
True
>>> 250 not in a
True
原文地址:https://www.cnblogs.com/ljwpython/p/14582281.html