python - Python-if语句下的多个条件
问题描述
我正在尝试编写一个函数来对给定数据集中的商品进行分类(我知道,以一种非常简单的方式)。
看起来像:
def classifier(x):
if ('smth' or 'smth' or 'smth') in x:
return 'class1'
elif ('smth' or 'smth' or 'smth') in x:
return 'class2'
所以,问题是某些条件不起作用。当我尝试单独检查条件时 - 一切正常。但是在函数中出现了问题。
我将 thing 函数与 pandas方法一起使用apply
:
data['classes'] = data['subj'].apply(lambda x: classifier(x))
解决方案
('smth' or 'smth' or 'smth')
从左到右执行连续的逻辑比较,但不检查它们中的每一个在目标序列中的出现。
要检查预定义列表(可迭代)中的任何值是否出现在目标序列中,请x
使用内置any
函数:
def classifier(x):
if any(i in x for i in ('a', 'b', 'c')):
return 'class1'
elif any(i in x for i in ('d', 'e', 'f')):
return 'class2'
推荐阅读
- python-3.x - 如何通过对 36x60 大小的数据进行训练的神经网络预测不同的数据?
- php - 如何取消设置 Laravel 块中的引用变量传递?
- vb.net - 代理授权标头在 HttpWebRequest 中不起作用,以防对 URL 的 Rest 请求
- oracle - 对任何子表行的更新将整个父表锁定在 oracle
- laravel - Moodle 自动登录插件 - 如何将用户引导至特定课程?
- android - RecycleView Kotlin 与 ArrayList 总是大小 = 0
- jestjs - jest@23.1.0 collectCoverageFrom 不选择根目录外的文件
- javascript - 为什么 2 位数字不适用于 Date.toLocaleTimeString?
- excel - 使用模式分割线
- html - 为什么进度 html 元素没有显示在电子邮件(gmail 或 hotmail)上,有什么方法可以显示它,为什么 Nunito google 字体在电子邮件上不起作用?