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

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

python如何為list實(shí)現(xiàn)find方法_python

作者:csdn_yuan88 ? 更新時(shí)間: 2022-07-27 編程語(yǔ)言

如何為list實(shí)現(xiàn)find方法

string類(lèi)型的話(huà)可用find方法去查找字符串位置:

a_list.find('a')

如果找到則返回第一個(gè)匹配的位置,如果沒(méi)找到則返回-1,而如果通過(guò)index方法去查找的話(huà),沒(méi)找到的話(huà)會(huì)報(bào)錯(cuò)。

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

方法1:獨(dú)立函數(shù)法

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))

缺點(diǎn):代碼太多,麻煩

方法2:if三元表達(dá)式(本質(zhì)同上)

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

優(yōu)點(diǎn):簡(jiǎn)單,明了

缺點(diǎn):item_list在上面出現(xiàn)兩次,想想一下,如果item_list是一個(gè)比較長(zhǎng)表達(dá)式的結(jié)果(或者函數(shù)結(jié)果),則會(huì)導(dǎo)致代碼過(guò)長(zhǎng),且會(huì)執(zhí)行2次

方法3:next(利用迭代器遍歷的第二個(gè)參數(shù))

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

缺點(diǎn):如果對(duì)迭代器不熟悉,不大好理解

優(yōu)點(diǎn):擴(kuò)展性好,if后面的條件可以不只是相等,可支持更為復(fù)雜的邏輯判斷

方法4:list元素bool類(lèi)型

''.join(map(str, map(int, item_list))).find(str(int(True)))

簡(jiǎn)單容易理解

Python List find方法報(bào)錯(cuò)

TypeError: 'str' does not support the buffer interface

deviceList[1].find('device')?

List使用find方法時(shí),報(bào)錯(cuò)誤:

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

上述語(yǔ)句改為:deviceList[1].find(b'device') 就好了,加了個(gè)小b

原文鏈接:https://blog.csdn.net/u011331731/article/details/107898634

欄目分類(lèi)
最近更新