给定一个对象列表,我试图根据给定的属性和基于该属性的表达式按降序对对象进行排序。向我的函数传递了一个参数,该参数将是我将用于比较的属性。我想要计算所选营养属性与卡路里属性的比率,例如(x.nutrient / x.calorie)。现在有几个我不得不厌倦的边缘案例。第一个x.calorie可能为零。第二,x.nutrient可能小于1.0,这将提供错误的结果,因为我希望x.nutrient的比率按降序给定x.calorie。如果您知道比使用if语句从函数参数中选择属性更好的方法,则可以加分。例如,营养素可以是脂肪、碳水化合物、蛋白质,如果我的函数传递给nutrient=fat,x.nutrient != x.fat。食品类数据成员,名称,蛋白质,碳水化合物,脂肪,卡路里,派别,protein_calories,carbs_calories,fat_calories。我想根据特定营养素(“蛋白质”、“碳水化合物”或“脂肪”)的卡路里百分比对食物列表进行排序,该列表需要按位置排序。
我试过使用attrgetter,它不允许我划分属性。我尝试了一个lambda函数,在这个函数中我缩放了值,但仍然没有按正确的顺序对列表进行归一化。
def sort_food_list(foods, nutrient):
if nutrient == 'protein':
foods.sort(key=lambda x: (x.protein * 100) / x.calories if (x.calories * 100) != 0 else 0, reverse=True)
if nutrient == 'carbs':
foods.sort(key=lambda x: (x.carbs * 100) / (x.calories * 100) if x.calories != 0 else 0, reverse=True)
if nutrient == 'fat':
foods.sort(key=lambda x: (x.fat * 100) / (x.calories * 100) if x.calories != 0 else 0, reverse=True)发布于 2019-06-05 16:41:27
试一下下面的代码。它涵盖了您提出的大部分观点。
class Food:
def __init__(self, name, protein, carbs, fat, calories=0):
self.name = name
self.protein = protein
self.carbs = carbs
self.fat = fat
self.calories = calories
def __repr__(self):
return '[name: {} protein: {} carbs: {} fat: {} calories: {}]'.format(self.name, self.protein, self.carbs,
self.fat, self.calories)
foods = [Food('F1', 12, 34, 56, 1), Food('F2', 11, 4, 16, 11), Food('F3', 11, 5, 56, 11), Food('F4', 1, 277, 3, 4),
Food('F5', 1234, 77, 333)]
def sort_foods(foods, nutrient):
foods.sort(key=lambda x: ((getattr(x, nutrient) * 100) / x.calories) if x.calories else 0, reverse=True)
sort_foods(foods, 'fat')
print('By fat')
print(foods)
print()
print('By protein')
sort_foods(foods, 'protein')
print(foods)
print()
print('By carbs')
sort_foods(foods, 'carbs')
print(foods)https://stackoverflow.com/questions/56437803
复制相似问题