首页 > 解决方案 > 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))

标签: pythonstringif-statement

解决方案


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

推荐阅读