Python 2 7 如何判斷物件是否為可迭代?

2021-08-16 19:12:19 字數 445 閱讀 2878

對於乙個物件,如果可以通過for迴圈遍歷它,那麼就稱這個物件為「可迭代」的。

其實我們已經知道list和tuple型別是可迭代的,但是有沒有一種方法可以直觀的判斷出來呢?這就用到了collenctions模組的iterable型別。

首先匯入collections模組下的iterable型別,然後通過isinstance返回boolean值。「可迭代」返回「true」,「不可迭代」返回「false」。

>>> from collections import iterable

>>> isinstance ('abc',iterable)

true

>>> isinstance (123,iterable)

false

>>> isinstance ([1,2,3],iterable)

true

python2 7換行 Python2 7基礎語法

1.建立檔案xx.py usr bin python3 print hello,world 2.linux下執行 python hello.py 3.編碼 預設字串unicode 設定編碼 coding utf 8 4.識別符號 第乙個字元必須是字母表中字母或下劃線 識別符號的其他的部分有字母 數字...

python2 7是什麼 python2 7是什麼

pyton2.7是python在2010年發布的乙個版本。python 是乙個高層次的結合了解釋性 編譯性 互動性和物件導向的指令碼語言,具有很強的可讀性,相比其他語言經常使用英文關鍵字,其他語言的一些標點符號,它具有比其他語言更有特色語法結構。下面來解釋一下python這門語言 python是一種...

python2 7中文編碼 python2 7

我從外部api中獲得了乙個字串 u4ece u8d77 u70b9 u5411 u6b63 u5357 u65b9 u5411 u51fa u53d1,u884c u9a76170 u7c73,u76f4 u884c u8fdb u5165 u4e2d u5173 u6751 u4e1c u8def...