如何检查特定类型的元组或列表? [英] How to check a specific type of tuple or list?

查看:95
本文介绍了如何检查特定类型的元组或列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设

var = ('x', 3)

如何检查变量是否是只有两个元素的元组,第一个是str类型,另一个是python中的int类型? 我们可以只使用一张支票吗? 我想避免这种情况-

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

推荐答案

这是一个简单的单行代码:

Here's a simple one-liner:

isinstance(v, tuple) and list(map(type, v)) == [str, int]

尝试一下:

>>> 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

这篇关于如何检查特定类型的元组或列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆