How to check a specific type of tuple or list?

yas*_*eth 5 python types tuples isinstance

Suppose,

var = ('x', 3)
Run Code Online (Sandbox Code Playgroud)

How to check if a variable is a tuple with only two elements, first being a type str and the other a type int in python? Can we do this using only one check? I want to avoid this -

if isinstance(var, tuple):
    if isinstance (var[0], str) and (var[1], int):
         return True
return False
Run Code Online (Sandbox Code Playgroud)

ekh*_*oro 7

这是一个简单的单行:

isinstance(v, tuple) and list(map(type, v)) == [str, int]
Run Code Online (Sandbox Code Playgroud)

试试看:

>>> def check(v):
        return isinstance(v, tuple) and list(map(type, v)) == [str, int]
...
>>> check(0)
False
>>> check(('x', 3, 4))
False
>>> check((3, 4))
False
>>> check(['x', 3])
False
>>> check(('x', 3))
True
Run Code Online (Sandbox Code Playgroud)


vis*_*isc 0

考虑到元组的长度是可变的,您将找不到一种方法来检查所有类型的此实例。你的方法有什么问题吗?很清楚它的作用并且适合您的使用。AFAIK,你不会找到漂亮的衬里。

而且你确实有一个衬垫......从技术上讲:

def isMyTuple(my_tuple):
    return isinstance(my_tuple,(tuple, list)) and isinstance(my_tuple[0],str) and isinstance(my_tuple[1],int)

var = ('x', 3)

print isMyTuple(var)
Run Code Online (Sandbox Code Playgroud)

如果您要多次执行此检查,则调用该方法就是DRY