新西兰服务器

python怎么为list实现find方法


python怎么为list实现find方法

发布时间:2022-05-30 16:38:27 来源:高防服务器网 阅读:89 作者:iii 栏目:开发技术

这篇文章主要介绍“python怎么为list实现find方法”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“python怎么为list实现find方法”文章能帮助大家解决问题。

如何为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怎么为list实现find方法”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注高防服务器网行业资讯频道,小编每天都会为大家更新不同的知识点。

[微信提示:高防服务器能助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。

[图文来源于网络,不代表本站立场,如有侵权,请联系高防服务器网删除]
[