if语句下的Python-Multiple条件

nut*_*ker 1 python string if-statement

我正在尝试编写一个函数,该函数将对给定数据集中的商品进行分类(我知道这是非常简单的方式)。

看起来像:

def classifier(x):
    if ('smth' or 'smth' or 'smth') in x:
        return 'class1'
    elif ('smth' or 'smth' or 'smth') in x:
        return 'class2'
Run Code Online (Sandbox Code Playgroud)

因此,问题在于某些条件不起作用。当我尝试分别检查条件时-一切正常。但是在函数中出现了问题。

我将事物功能与pandas apply-method一起使用:

data['classes'] = data['subj'].apply(lambda x: classifier(x))
Run Code Online (Sandbox Code Playgroud)

Rom*_*est 5

('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'
Run Code Online (Sandbox Code Playgroud)