Home > database >  How do I put a break in a single-line for loop
How do I put a break in a single-line for loop

Time:01-20

I am working on a discord bot and returning a list of item. Unfortunately, if the list exceeds 25 items, it throws an error. I want break the loop after 25 loops. Below is a sample of code provided in the discord.py documentation; the for loop is a single line and does not work if I try to modify it:

async def fruit_autocomplete(
interaction: discord.Interaction,
current: str,
) -> List[app_commands.Choice[str]]:
    fruits = ['Banana', 'Pineapple', 'Apple', 'Watermelon', 'Melon', 'Cherry']
    return [
        app_commands.Choice(name=fruit, value=fruit)
        for fruit in fruits if current.lower() in fruit.lower()
    ]

CodePudding user response:

Use the itertools.islice to take first N results from a generator (...):

async def fruit_autocomplete(
interaction: discord.Interaction,
current: str,
) -> Iterable[app_commands.Choice[str]]:
    fruits = ['Banana', 'Pineapple', 'Apple', 'Watermelon', 'Melon', 'Cherry']
    return itertools.islice(
        (app_commands.Choice(name=fruit, value=fruit)
        for fruit in fruits if current.lower() in fruit.lower())
    , 25)

If desiring a List as result, wrap above return with list(...).


With just a list, slice with [:N]:

async def fruit_autocomplete(
interaction: discord.Interaction,
current: str,
) -> List[app_commands.Choice[str]]:
    fruits = ['Banana', 'Pineapple', 'Apple', 'Watermelon', 'Melon', 'Cherry']
    current = current.lower()
    return [app_commands.Choice(name=f, value=f)
            for f in fruits if current in f.lower()][:25]
  • Related