您现在的位置是:网站首页> 编程资料编程资料
python如何为list实现find方法_python_
2023-05-26
381人已围观
简介 python如何为list实现find方法_python_
如何为list实现find方法
string类型的话可用find方法去查找字符串位置:
a_list.find('a')如果找到则返回第一个匹配的位置,如果没找到则返回-1,而如果通过index方法去查找的话,没找到的话会报错。
如果我们希望在list中也使用find呢?
方法1:独立函数法
def list_find(item_list, find_item): if find_item in item_list: return item_list.index(find_item) return -1 item_list=[1,2,3] print(list_find(item_list,1),list_find(item_list,4))
缺点:代码太多,麻烦
方法2:if三元表达式(本质同上)
item_list.index(find_item) if find_item in item_list else -1
优点:简单,明了
缺点:item_list在上面出现两次,想想一下,如果item_list是一个比较长表达式的结果(或者函数结果),则会导致代码过长,且会执行2次
方法3:next(利用迭代器遍历的第二个参数)
next((item for item in item_list if item==find_item ),-1)
缺点:如果对迭代器不熟悉,不大好理解
优点:扩展性好,if后面的条件可以不只是相等,可支持更为复杂的逻辑判断
方法4:list元素bool类型
''.join(map(str, map(int, item_list))).find(str(int(True)))
简单容易理解
Python List find方法报错
TypeError: 'str' does not support the buffer interface
deviceList[1].find('device')
List使用find方法时,报错误:
TypeError: 'str' does not support the buffer interface
In python 3, bytes strings and unicodestrings are now two different types. Bytes strings are b"" enclosed strings
上述语句改为:deviceList[1].find(b'device') 就好了,加了个小b
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
您可能感兴趣的文章:
相关内容
- python如何查找列表中元素的位置_python_
- Python数组变形的几种实现方法_python_
- Python实现多脚本处理定时运行_python_
- Pytorch模型定义与深度学习自查手册_python_
- Python excel合并居中值相同的单元格实例代码_python_
- Pandas处理时间序列数据操作详解_python_
- pytorch常用函数定义及resnet模型修改实例_python_
- python保存字典数据到csv文件的完整代码_python_
- python深度学习标准库使用argparse调参_python_
- python中的opencv 图像分割与提取_python_
