在同一个变量中包含1个以上单词的条件语句

时间:2018-07-24 05:34:56

标签: python if-statement conditional

我试图根据另一个变量根据各种业务规则创建一个变量。请参见下面的示例。当我只处理一个单词时,我需要使用以下代码:

  physical = ['light', 'sedentary', 'medium', 'heavy']

  def matcher(x):
      for i in physical:
          if i.lower() in x.lower():
             return i
          else:
             return 'other'

我的问题是,当一个句子中有多个单词匹配时,在这种情况下,我想称呼mix。例如,如果一个句子中的多个单词出现在第一个句子中,则为'mix'

  Physical Demand                                          Result
    Light to medium with occasional heavy  levels           mix                        
    Light lifting                                           light
    Medium effort required when lifting                     medium

tks。

2 个答案:

答案 0 :(得分:1)

您将希望跟踪以前是否看到过另一个值,而不是返回看到的第一个值

例如

 def matcher(x):
    val = None
    for p in physical:
        for y in x.split():  # assuming x is a string 
            if p == y.lower():  # physical elements are already lowercase 
                if val is not None: 
                    # val already has a value, so you have more than one physical element in x 
                    return 'mix' 
                val = p
        return val if val else 'other'

答案 1 :(得分:1)

您需要选中所有项以返回mix,而不是仅检查一项即可直接返回。接下来是可行的代码,仅供参考。

physical = ['light', 'sedentary', 'medium', 'heavy']

def matcher(x):
    l = [item for item in physical if item.lower() in x.lower()]
    length = len(l)

    if length == 0:
        return 'other'
    elif length == 1:
        return l[0]
    else:
        return 'mix'

print(matcher('Light to medium with occasional heavy  levels'))
print(matcher('Light'))
print(matcher('Medium'))
print(matcher('abcde'))

输出:

mix
light
medium
other