- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我们如何测试 X 是否像列表/元组一样嘎嘎作响?
我的意思是我们可以用 0 和 1(等)对其进行子集化,尽管它不能是字符串(也可以是子集)。
我想测试 hasattr(X, '__iter__')
和 not isinstance(X, str)
,但这意味着字典仍然会通过,而我所做的不想这样。然后你也可以测试它不是字典,但我不太确定字典的子类等。
在这个简单的规范下,是否有更正式的方法来测试某些东西是否像列表或元组?
例如允许的输入应该是:
'emailaddr' --> ('emailaddr', 'emailaddr')
('emailaddr', 'alias')
['emailaddr', 'alias']
SequenceThing('emailaddr', 'alias')
最佳答案
您想检查一个值是否为 sequence ?
An iterable which supports efficient element access using integer indices via the getitem() special method and defines a len() method that returns the length of the sequence. Some built-in sequence types are list, str, tuple, and bytes. Note that dict also supports getitem() and len(), but is considered a mapping rather than a sequence because the lookups use arbitrary immutable keys rather than integers.
旧方法(在 2.7 中弃用):
import operator
print operator.isSequenceType(x)
新方式:
import collections
print isinstance(x, collections.Sequence)
它们不等价 - 后者更准确,但自定义类型需要为 registered有了它。
此外,根据这两种定义,字符串都是序列。您可能希望对 basestring
进行特殊处理。
关于python - 如何测试 X 是否像列表/元组一样嘎嘎作响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29855699/
我是一名优秀的程序员,十分优秀!