gpt4 book ai didi

python - 如何测试 X 是否像列表/元组一样嘎嘎作响

转载 作者:太空宇宙 更新时间:2023-11-03 14:19:19 25 4
gpt4 key购买 nike

我们如何测试 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com