列表元素的访问和计数
通过索引直接访问元素
我们可以通过索引直接访问元素,索引的区间在[0,列表长度-1]这个范围。超过这个范围则会抛出异常
Index()函数获得指定元素在列表中首次出现的索引
Index()可以获取指定元素首次出现的索引位置。语法是:index(value,[start,[end]]).其中,start和end指定了搜索的范围
Count()获得指定元素在列表中出现的次数
Count()可以返回指定元素在列表中出现的次数
Len()返回列表长度
Len()返回列表长度,即列表中包含元素的个数
成员资格判断
判断列表中是否存在指定的元素,我们可以使用count()方法,返回0则表示不存在,返回大于0则表示存在,但是,一般我们会使用更加简洁的in关键字来判断,直接返回True或False。
>>> a = [10,20,30] >>> a[1] 20 >>> a[20] Traceback (most recent call last): File "<pyshell#21>", line 1, in <module> a[20] IndexError: list index out of range >>> >>> a.index(20) 1 >>> a.index(20,1) 1 >>> a.index(20,0,2) #从0-2范围获得首次出现20的位置 1 >>> >>> a.count(20) 1 >>> >>> len(a) 3 >>> >>> 20 in a True >>> 100 not in a True >>> 'a' in 'bac' True >>> a.count(20) 1 >>> a.count(20)>0 True >>> a.count(99)>0 False >>> |