python - 检查对象是数字还是 bool 值

标签 python python-2.7

Design a logical expression equivalent to the following statement:

x is a list of three or five elements, the second element of which is the string 'Hip' and the first of which is not a number or Boolean.

我有什么:

x = ['Head', 'Hip', 10]
print x[1] is 'Hip'

我的问题:如何检查它是 bool 值还是数字?

最佳答案

回答具体问题:

isinstance(x[0], (int, float))

这会检查 x[0] 是否是元组 (int, float) 中任何类型的实例。

您也可以在其中添加 bool,但这不是必需的,因为 bool 本身就是 int 的子类。

文档引用:


要评论您当前的代码,您不应依赖 interning of short strings .您应该使用 == 运算符比较字符串:

x[1] == 'Hip'

关于python - 检查对象是数字还是 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15019830/

相关文章:

python - '%.*g' % (6,k) 在 python 中如何工作

python - 尝试使用 BeautifulSoup 从我的代码中使用 Xpath 进行网页抓取

python - 操作列表列表和字典

Python解析CSV忽略带双引号的逗号

python - 在提交对象之前从 SqlAlchemy 获取主键

python - 有没有办法在 matplotlib 的部分子图中共享 Y 轴?

python - 如何在 Jupyter 笔记本的同一单元格中包含多个交互式小部件

python - 在 fractions.Fraction 子类中调用 super().__init__(*args, **kwargs) 只接受要初始化的实例

python - 根据 pandas 数据框中的顺序重新排列列

python - PyQt5虚拟键盘(TypeError : missing 1 required positional argument)