python如何为list实现find方法
作者:csdn_yuan88 时间:2022-01-14 09:15:56
如何为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
来源:https://blog.csdn.net/u011331731/article/details/107898634
标签:python,list,find
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
解决python3中cv2读取中文路径的问题
2023-05-17 18:52:10
求任意自然数内的素数
2009-10-15 12:21:00
perl批量查询ip归属地的方法代码
2023-08-11 22:53:54
Tensorflow2.4从头训练Word Embedding实现文本分类
2023-05-22 20:03:17
白鸦:如何设计用户体验?
2008-01-03 16:53:00
通过不同的CSS设计字体大小来提高用户体验
2008-12-10 19:17:00
python 给图像添加透明度(alpha通道)
2021-05-04 04:57:22
![](https://img.aspxhome.com/file/2023/3/98983_0s.jpg)
Pyhon Flask框架:第一个Flask程序
2023-01-09 16:06:34
![](https://img.aspxhome.com/file/2023/3/81833_0s.png)
如何在Access 2007数据库中添加附件
2008-11-21 12:32:00
Python环境下安装使用异步任务队列包Celery的基础教程
2023-08-23 23:06:48
python之线程通过信号pyqtSignal刷新ui的方法
2022-01-03 22:28:45
![](https://img.aspxhome.com/file/2023/5/70165_0s.jpg)
python猜数字小游戏实现代码
2022-04-20 19:01:43
![](https://img.aspxhome.com/file/2023/5/98805_0s.jpg)
Python 变量类型详解
2022-06-23 00:44:55
![](https://img.aspxhome.com/file/2023/1/91961_0s.jpg)
M1芯片Mac上Anaconda的暂时替代(miniforge)
2022-12-12 00:32:43
![](https://img.aspxhome.com/file/2023/2/93872_0s.jpg)
asp 延时 页面延迟的三种方法
2011-03-31 11:04:00
缓存是如何实现的?
2009-11-01 15:35:00
获得MySQL改变字符集的方案
2010-08-31 14:53:00
ASP常用函数:IsBlank()
2008-09-28 13:21:00
python Windows最新版本安装教程
2023-02-25 21:09:52
![](https://img.aspxhome.com/file/2023/4/93434_0s.png)
Scrapy元素选择器Xpath用法汇总
2021-09-11 11:42:58