简体   繁体   中英

Conditional statements with more than 1 word in the same variable

I am trying to create a variable based in various business rules from another variable. Please see example below. When I am dealing with only one word I need to use as a condition I use the following code:

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

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

My issue is when that are multiple words that match in a sentence, in this specific cases I want to call mix . For example if more than one of the words appear in a sentence as on the first sentence then 'mix'

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

tks.

You'll want to track if you have previously seen another value rather than returning the first value seen

For example

 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'

You need to check all item to return mix instead of directly return after just check one item. Next is a workable code, FYI.

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

Output:

mix
light
medium
other

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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