網站首頁 編程語言 正文
如何為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
相關推薦
- 2022-09-22 Apriori算法的實現
- 2022-06-12 如何在React項目中使用AntDesign_React
- 2022-04-28 python的字典和集合你了解嗎_python
- 2022-09-05 Hbase 之KeyValue結構詳解
- 2022-08-11 python?groupby函數實現分組后選取最值_python
- 2022-02-21 React事件綁定詳解_React
- 2022-06-02 Android系統view與SurfaceView的基本使用及區別分析_Android
- 2022-07-07 C#操作注冊表之Registry類_C#教程
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支