python怎么为list实现find方法

这篇文章主要介绍“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方法”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注蜗牛博客行业资讯频道,小编每天都会为大家更新不同的知识点。

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:niceseo99@gmail.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

评论

有免费节点资源,我们会通知你!加入纸飞机订阅群

×
天气预报查看日历分享网页手机扫码留言评论电报频道链接