![]() |
list comprehension - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: list comprehension (/thread-37707.html) |
list comprehension - 3lnyn0 - Jul-11-2022 Hi! I try to modify the function below with list comprehation. But I don't now how to write that else secvantion This: def cakes(recipe, available): list_value = [ ] for key,value in recipe.items(): if key in available: a = int(available[key]) // int(value) list_value.append(a) else: return 0 list_value.sort() return list_value[0]In this: def cakes(recipe, available): list_value = [int(available[key]) // int(value) for key,value in recipe.items() if key in available else return 0 ].sort() return list_value[0] RE: list comprehension - deanhystad - Jul-12-2022 def cakes(recipe, available): values = [int(available[key]) // int(value) for key, value in recipe.items() if key in available] if len(values) > 0: values.sort() return values[0] return 0 RE: list comprehension - DeaD_EyE - Jul-12-2022 Quote:[int(available[key]) // int(value) for key,value in recipe.items() if key in available else return 0 ].sort() The sort method of a list , does not return the list. Instead, the list is sorted inline and returns None , which is assigned to list_value .You can wrap around the whole list comprehension with the sorted function. The sorted function returns a new list, where the original list is not modified.If you want to get the highest number of a sequence, use the max function.To get the lowest number, use min .Example: from __future__ import annotations def cakes(recipe: dict, available: dict) -> int | None: values = [ int(available[key]) // int(value) for key, value in recipe.items() if key in available ] if values: return min(values)Annotations: They are not mandatory, but can give you a hint, which types should be used and which types return. For example, an empty recipe will return None . A valid recipe will return an int .
RE: list comprehension - Gribouillis - Jul-12-2022 You can avoid checking if values is empty by using the 'default' argument in min() >>> min([], default=0) 0So def cakes(recipe, available): return min( (int(available[key]) // int(value) for key, value in recipe.items() if key in available), default=0) RE: list comprehension - DeaD_EyE - Jul-12-2022 @Gribouillis, thanks. The blacked Version is easier to read: def cakes(recipe, available): return min( ( int(available[key]) // int(value) for key, value in recipe.items() if key in available ), default=0, )The parenthesis for the Generator Expression is not mandatory. |