脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|shell|

服务器之家 - 脚本之家 - Python - python如何为list实现find方法

python如何为list实现find方法

2023-02-22 11:58csdn_yuan88 Python

这篇文章主要介绍了python如何为list实现find方法,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

如何为list实现find方法

string类型的话可用find方法去查找字符串位置:

?
1
a_list.find('a')

如果找到则返回第一个匹配的位置,如果没找到则返回-1,而如果通过index方法去查找的话,没找到的话会报错。

如果我们希望在list中也使用find呢?

方法1:独立函数法

?
1
2
3
4
5
6
7
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三元表达式(本质同上)

?
1
item_list.index(find_item) if find_item in item_list else -1

优点:简单,明了

缺点:item_list在上面出现两次,想想一下,如果item_list是一个比较长表达式的结果(或者函数结果),则会导致代码过长,且会执行2次

方法3:next(利用迭代器遍历的第二个参数)

?
1
next((item for item in item_list if item==find_item ),-1)

缺点:如果对迭代器不熟悉,不大好理解

优点:扩展性好,if后面的条件可以不只是相等,可支持更为复杂的逻辑判断

方法4:list元素bool类型

?
1
''.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

延伸 · 阅读

精彩推荐