这是我通常所做的,以确定输入是一个列表/元组-而不是一个str。因为很多次我偶然发现错误,其中一个函数错误地传递了一个str对象,而目标函数在lst中执行x,假设lst实际上是一个列表或元组。
assert isinstance(lst, (list, tuple))
我的问题是:有没有更好的方法来实现这个目标?
这是我通常所做的,以确定输入是一个列表/元组-而不是一个str。因为很多次我偶然发现错误,其中一个函数错误地传递了一个str对象,而目标函数在lst中执行x,假设lst实际上是一个列表或元组。
assert isinstance(lst, (list, tuple))
我的问题是:有没有更好的方法来实现这个目标?
当前回答
我在tensorflow中找到了这样一个名为is_sequence的函数。
def is_sequence(seq):
"""Returns a true if its input is a collections.Sequence (except strings).
Args:
seq: an input sequence.
Returns:
True if the sequence is a not a string and is a collections.Sequence.
"""
return (isinstance(seq, collections.Sequence)
and not isinstance(seq, six.string_types))
我已经核实了,它符合你的需求。
其他回答
就这么做
if type(lst) in (list, tuple):
# Do stuff
以“鸭子打字”的方式,怎么样
try:
lst = lst + []
except TypeError:
#it's not a list
or
try:
lst = lst + ()
except TypeError:
#it's not a tuple
分别。这避免了isinstance / hasattr自省的事情。
你也可以反过来检查:
try:
lst = lst + ''
except TypeError:
#it's not (base)string
所有变量实际上并不改变变量的内容,而是意味着重新赋值。我不确定在某些情况下这是否不可取。
有趣的是,如果lst是一个列表(不是元组),使用“in place”赋值+=在任何情况下都不会引发TypeError。这就是为什么作业是这样做的。也许有人能解释一下原因。
H = "Hello"
if type(H) is list or type(H) is tuple:
## Do Something.
else
## Do Something.
我倾向于这样做(如果我真的,真的必须这么做的话):
for i in some_var:
if type(i) == type(list()):
#do something with a list
elif type(i) == type(tuple()):
#do something with a tuple
elif type(i) == type(str()):
#here's your string
在python中>3.6
import collections
isinstance(set(),collections.abc.Container)
True
isinstance([],collections.abc.Container)
True
isinstance({},collections.abc.Container)
True
isinstance((),collections.abc.Container)
True
isinstance(str,collections.abc.Container)
False