python - 如何检查特定类型的元组或列表?

标签 python types tuples isinstance

假设,

var = ('x', 3)

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

if isinstance(var, tuple):
    if isinstance (var[0], str) and (var[1], int):
         return True
return False

最佳答案

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

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

关于python - 如何检查特定类型的元组或列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32770725/

相关文章:

swift - 难以理解复杂的快速关联类型声明

javascript - Flow javascript混合类型数组不能使用数组函数

python - 比较元组列表 - 无论位置如何都相等

python - Django 用户创建表单需要 keyerror

haskell - 如何将 Haskell 类型强制转换为更通用的类型

python argparse - 使用带有 nargs 的列表选项显示困惑的帮助消息

python 错误: tuples indices must be integers or slices not tuples

一组类属性的元组的 Python 简写

python - 如何在 Google Drive API 中执行不区分大小写的标题搜索?

python - 安装 gruobipy 包 - 错误