日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

python 判断数字序列是否合法_Python:检查对象是否是序列

發(fā)布時間:2025/3/15 python 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python 判断数字序列是否合法_Python:检查对象是否是序列 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

In python is there an easy way to tell if something is not a sequence? I tried to just do:

if x is not sequence but python did not like that

解決方案

iter(x) will raise a TypeError if x cannot be iterated on -- but that check "accepts" sets and dictionaries, though it "rejects" other non-sequences such as None and numbers.

On the other hands, strings (which most applications want to consider "single items" rather than sequences) are in fact sequences (so, any test, unless specialcased for strings, is going to confirm that they are). So, such simple checks are often not sufficient.

In Python 2.6 and better, abstract base classes were introduced, and among other powerful features they offer more good, systematic support for such "category checking".

>>> import collections

>>> isinstance([], collections.Sequence)

True

>>> isinstance((), collections.Sequence)

True

>>> isinstance(23, collections.Sequence)

False

>>> isinstance('foo', collections.Sequence)

True

>>> isinstance({}, collections.Sequence)

False

>>> isinstance(set(), collections.Sequence)

False

You'll note strings are still considered "a sequence" (since they are), but at least you get dicts and sets out of the way. If you want to exclude strings from your concept of "being sequences", you could use collections.MutableSequence (but that also excludes tuples, which, like strings, are sequences, but are not mutable), or do it explicitly:

import collections

def issequenceforme(obj):

if isinstance(obj, basestring):

return False

return isinstance(obj, collections.Sequence)

Season to taste, and serve hot!-)

總結(jié)

以上是生活随笔為你收集整理的python 判断数字序列是否合法_Python:检查对象是否是序列的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。