代码之家  ›  专栏  ›  技术社区  ›  Estrobelai

Python:数组中价格高于平均值的所有项目

  •  0
  • Estrobelai  · 技术社区  · 11 月前

    给定一个食物名称及其卡路里和价格信息的列表,格式为[名称、卡路里、价格],我想在Python中创建一个方法,返回一个新数组中价格高于平均值的所有项目。

    假设上面的输入是以下数组:

    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创建方法,但作为Python的初学者,我不确定最佳解决方案是什么:

    def get_food_selection(food_items):
    return sorted(overlap_items)
    

    任何帮助都将不胜感激。

    1 回复  |  直到 11 月前
        1
  •  2
  •   Allan Wind    11 月前

    首先计算平均值,这里使用 statistics.mean() ,然后选择感兴趣的元素。您可以使用列表解析来构建相关列表:

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

    或使用 map() filter() :

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

    如果你计算自己的平均值,一定要考虑如果传入一个空数组会发生什么。

    推荐文章