pythonarrayslist

Python: all items that have a higher than average price in array


As part of a Python course I´m taking I wonder whether anyone can help me with the following question: given a list of food names along with their calories and prices information in the format of [name, calories, price] I want to create a function in Python that returns all items in a new array that have a higher than average price.

Say the input for the above is the following array:

input =[
['ABUELO SUCIO (16oz)',400,26],
['Chick-fil-A Chicken Sandwich',400,6],
['Chicken in Lettuce Cups',900,19],
['Classic French Dip',900,16],
['Grilled Chicken Teriyaki',400,18],
['Medium 8 pc Wing Combo',300,10],
['Pad See You',1000,19],
['Tea Leaf Rice',400,15],
['Udon',300,12],
['Very Cherry Ghirardelli Chocolate Cheesecake',900,10]
]

I am trying to create the method with the def below but not sure what the optimal solution is as am a beginner in Python:

def get_food_selection(food_items):
return sorted(overlap_items)

Any help is appreciated.


Solution

  • First calculate the average, here using statistics.mean(), then select the elements of interest. You can use list comprehensions to built the relevant lists:

    import statistics
    
    input = [
        ['ABUELO SUCIO (16oz)',400,26],
        ['Chick-fil-A Chicken Sandwich',400,6],
        ['Chicken in Lettuce Cups',900,19],
        ['Classic French Dip',900,16],
        ['Grilled Chicken Teriyaki',400,18],
        ['Medium 8 pc Wing Combo',300,10],
        ['Pad See You',1000,19],
        ['Tea Leaf Rice',400,15],
        ['Udon',300,12],
        ['Very Cherry Ghirardelli Chocolate Cheesecake',900,10]
    ]
    
    def higher_than_average(l):
        average = statistics.mean([i[1] for i in l])
        return [i for i in l if i[1] >= average]
    
    print(higher_than_average(input))
    

    Or use map() and filter():

    def higher_than_average(l):
        average = statistics.mean(map(lambda i: i[1], l))
        return list(filter(lambda i: i[1] > average, l))
    

    Make sure you think about what should happen if an empty array is being passed in if you calculate your own average.