日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

python如何為list實現find方法_python

作者:csdn_yuan88 ? 更新時間: 2022-07-27 編程語言

如何為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

相關推薦

欄目分類
最近更新