Count方法
此方法用于统计列表中某个元素出现的次数,其基本语法格式为:
c_list.count(obj)
其中,c_list代表列表名,obj 表示判断是否存在的元素。
下面代码示范了 count() 方法的用法:
c_list = [20, 'crazyit', 30, -4, 'crazyit', 3.4]
print(c_list.count('crazyit'))#统计crazyit出现的次数
print(c_list.count(20))
返回结果如下:
2
index()用法
index() 方法用于定位某个元素在列表中出现的位置(也就是索引),如果该元素没有出现,则会引发 ValueError 错误。
此方法的基本语法格式为:
c_list.index()
如下代码示范了 index() 方法的用法:
#index()用于定位某个元素在列表中出现的位置
print(c_list.index('crazyit'))
# #从索引1处开始,定位crazyit出现的位置
print(c_list.index('crazyit',2))