Python迭代器Iterable判斷方法解析
更新時間:2020年03月16日 10:27:17 作者:Mr_choa
這篇文章主要介紹了Python迭代器Iterable判斷方法解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
迭代器(Iterable):能直接作用于for循環(huán)的對象,統(tǒng)稱可迭代對象。例如:list、tuple、set、str、generator都是可迭代對象。
1、如何判斷一個對象是否可迭代:
# 如何判斷一個對象是可迭代對象 #導入collections.abc模塊中的Iterable對象 import collections.abc # 判斷str是否可迭代 a=isinstance('abc',collections.abc.Iterable) # 打印迭代結果 print(a) # 導入collections.abc模塊 import collections.abc # 判斷str是否可迭代 a=isinstance('abc',collections.abc.Iterable) # 打印迭代結果 print(a)
結果:
True
True
2、使用迭代查找list最大值和最小值,結果返回一個tuple
#定義Findmax_list,使用迭代查找list最大值和最小值,返回一個tuple def Findmax_list(L:list): max_number = L[0] min_number = L[0] # list可迭代,做遍歷,查找最大值和最小值 for i in L: max_number=max(max_number,i) min_number=min(min_number,i) # 返回一個tuple return max_number, min_number # 定義一個list test_list=[1,6,2,3,4,8] # 調用Findmax_list result=Findmax_list(test_list) # 打印tuple結果 print(result) # 測試返回結果 print(type(result))
結果:
(8, 1)
<class 'tuple'>
Process finished with exit code 0
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Python selenium的安裝和下載谷歌瀏覽器鏡像驅動
Selenium是一個用于web自動化測試的框架,在使用Ajax請求數據的頁面中,會出現 sign ,token等密鑰,借助使用Selenium框架來實現數據爬取很不錯,本文給大家介紹Python selenium的安裝和下載谷歌瀏覽器鏡像驅動,需要的朋友可以參考下2022-11-11解決ImportError:cannot import name ‘Flatten‘&nb
這篇文章主要介紹了解決ImportError:cannot import name ‘Flatten‘ from ‘torch.nn‘問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06