首页 > IT职业 > IT生活 > Python中list的查找
Python中查找list中某个固定元素是常有的事,对于两种不同的查找有两种不同的解决方案,见下。
list自带的方法index可以找出某元素在list中首次出现的位置。用法为
list.index(element, start, end)
其中,start为开始搜索的位置,默认为0;end为结束搜索的位置,默认为list长度。示例:
l = [1, 2, 3, 1, 5, 6] res = l.index(1)print(res, type(res))
则输出结果为
0 <class 'int'>
若限定搜索范围(可只指定其中某一个):
l = [1, 2, 3, 1, 5, 6] res = l.index(1, 1, 5)print(res, type(res))
则输出结果为
3 <class 'int'>
若想找出某一元素在该list中的所有出现位置,则用一个循环来简单的实现。
l = [1, 2, 3, 1, 5, 6] res = [idx for idx, i in l if i == 1]print(res, type(res))
则输出结果为
[0, 3] <class 'list'>
作者:就是suixin
链接:https://www.jianshu.com/p/9bc587b37ead
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/3127/viewspace-2818517/ ,如需转载,请注明出处,否则将追究法律责任。