Home > Back-end >  Convert for loops to list comprenshion
Convert for loops to list comprenshion

Time:08-29

is there a way to convert the below statements to one list comprenshion

def find_gender(gender_data):
    gender = {
        "Women": ["women", "women's", "female"],
        "Men": ["men", "men's", "male"],
    }
    gender_data = gender_data.lower()
    for gender_key, gender_items in gender.items():
        for word in gender_items:
            if gender_data.find(word) is not -1:
                return gender_key
    return "Unisex"

the output should be only one string i.e 'Men' or 'Women' or 'Unisex'

CodePudding user response:

As you want a single result, a list comprehension is a poor choice of tool. However, we can readily directly translate your loops into a generator expression, and pass that to next, providing a default value of 'Unisex'.

def find_gender(gender_data):
    gender = {
        "Women": ["women", "women's", "female"],
        "Men": ["men", "men's", "male"],
    }
    gender_data = gender_data.lower()
    
    return next((gender_key 
                 for gender_key, gender_items in gender.items() 
                 for word in gender_items
                 if gender_data.find(word) is not -1),
                'Unisex')

CodePudding user response:

def find_gender(gender_data): 
    gender_data = gender_data.lower()
    woman = ["women","women's","female"]
    man   = ["men"  ,"men's"  ,"male"  ]
    if any(s for s in woman if s in gender_data): return "Woman"
    if any(s for s in man   if s in gender_data): return "Men"
    return "Unisex"
  • Related