XymphosCraK
XymphosCraK

Reputation: 13

Python Conciseness: Comparing string to multiple sets with return value

Something that I've never found a concise way to do is to compare a string with multiple sets, or perhaps one long one that gives some meaningful output. This is my current code:

def input():  
    text = input("Choose a number: ").lower()  
    if "1" in text or "one" in text: return 1  
    elif "2" in text or "two" in text: return 2  
    ... and so on...  
    elif "9" in text or "nine" in text: return 9
    else: return 0  

My goal is to make it a bit more concise, considering how ugly it is right now.

Also, a little bit of a tag on question: is it faster to do this, or:

    if any(x in text for x in (["1", "one"])): return 1  

Which one is considered more mainstream?

Sorry; my Python is really entry-level.

--- EDIT ---

Apologies for the confusion; I actually meant something more generalisable, such as for this:

def input():  
        text = input("Give an input: ").lower()  
        if any(x in text for x in (["eggplant", "emoji", "purple"])): return 1  
        elif any(x in text for x in (["tomato", "red", "tomatina"])): return 2  
        ... and so on...  
        elif any(x in text for x in (["lettuce", "green", "avatar"])): return 9
        else: return 0  

Upvotes: 1

Views: 51

Answers (2)

user2390182
user2390182

Reputation: 73470

Depending on the regularity of your queries, you could use some kind of looping:

for i, s in enumerate('one two three four ... nine'.split(), 1):
  if str(i) in text or s in text:
    return i
return 0

Upvotes: 1

Michael Butscher
Michael Butscher

Reputation: 10959

I would create a normalization function for that:

_NORMALIZE_DICT = {
    "one": "1",
    "two": "2",
    ...
}

def normalize(test):
    return _NORMALIZE_DICT.get(test.lower(), test)

and then

def input():  
    text = normalize(input("Choose a number: "))
    try:
        return int(text)
    except ValueError:
        return 0

Upvotes: 0

Related Questions