vendredi 10 mars 2017

Python list comprehension: return value matching multiple if statements, else return other value

I'm working on list comprehension in python, and am having difficulty condensing my code into a single list comprehension statement.

I'm writing a function to search a list of movie dictionaries that looks like this:

    movies = [
    {
    "name": "Usual Suspects", 
    "imdb": 7.0,
    "category": "Thriller"
    },
    {
    "name": "Hitman",
    "imdb": 6.3,
    "category": "Action"
    },
    {
    "name": "Dark Knight",
    "imdb": 9.0,
    "category": "Adventure"
    }
    ]

I'm trying to write a function takes in an input of a movie name, checks the imdb score, and returns True if the score > 5.5, but returns false if the score doesn't meet this criteria.

Writing in traditional code, I accomplished this like the following:

    def good_movie(movie_name):
        for m in movies:        #for each item in movies...
            if m["name"] == movie_name:       #see if movie_name == "name", if it does...
                if m["imdb"] > 5.5:      # See if the movie's score is greater than 5.5...
                    return "True"      # If it is, return "true"
                else:        #otherwise
                    return "False"       #return false

I've been able to write this in list comprehension to return true, but can't get the function to work if I also want to return false when the movie doesn't meet the proper score criteria.

The short version that works is:

    def good_movie(movie_name):
        return ["True" for m in movies if m["name"] == movie_name if m["imdb"] > 5.5]

However, I'd like to be able to return a value of False if the movie_name doesn't meet both of the if statements listed here. I've tried it a few different ways, but can't figure out how to make it work.

Something like this DOESN'T work:

    def good_movie(movie_name):
        return ["True" if m["imdb"] > 5.5 and if m["name"] == movie_name else "False" for m in movies]

I thought maybe adding the "and" between the if statements would help (otherwise, it would think of the if statements as independent, rather than connected).

I've worked with this back and forth a number of times, but any assistance anyone could provide would help me better understand how these sorts of list comprehensions work in the future.

Thanks for you help!

Aucun commentaire:

Enregistrer un commentaire