简体   繁体   English

Python-if 语句下的多个条件

[英]Python-Multiple conditions under if statement

I am trying to write a function that will classify goods in a given dataset (in a very straightforward way, i know).我正在尝试编写一个函数来对给定数据集中的商品进行分类(我知道,以一种非常直接的方式)。

It looks like:看起来像:

def classifier(x):
    if ('smth' or 'smth' or 'smth') in x:
        return 'class1'
    elif ('smth' or 'smth' or 'smth') in x:
        return 'class2'

So, the problem is that some conditions do not work.所以,问题是某些条件不起作用。 When I try to check conditions separately - everything works.当我尝试单独检查条件时 - 一切正常。 But in the function something goes wrong.但是在函数中出了点问题。

I use thing function with a pandas apply -method:我将 thing 函数与 pandas apply -method 一起使用:

data['classes'] = data['subj'].apply(lambda x: classifier(x))

('smth' or 'smth' or 'smth') performs a consecutive logical comparison left-to-right, but not check for occurrence each of them within a target sequence. ('smth' or 'smth' or 'smth')从左到右执行连续的逻辑比较,但不检查它们在目标序列中的每个出现。

To check if any value from a predefined list (iterable) occurs within a target sequence x use builtin any function:要检查预定义列表(可迭代)中的任何值是否出现在目标序列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'

You could use this:你可以用这个:

def classifier(x):
    if 'smth' in x or 'smth' in x or 'smth' in x:
        return 'class1'
    elif 'smth' in x or 'smth' in x or 'smth' in x:
        return 'class2'

You have to check for each condition separately.您必须分别检查每个条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM