1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] python list comprehension -- two loops with three results?

Discussão em 'Python' iniciado por Stack, Setembro 12, 2024.

  1. Stack

    Stack Membro Participativo

    I can ask my question best by just giving an example. Let's say I want to use a list comprehension to generate a set of 3-element tuples from two loops, something like this:

    [ (y+z,y,z) for y in range(10) if y%2==0 for z in range(20) if z%3==0 ]


    This works, giving me

    [(0, 0, 0), (3, 0, 3), (6, 0, 6), (9, 0, 9), (12, 0, 12), (15, 0, 15), ... ]


    I am wondering, though, if there is a way to do it more cleanly, something to the effect of

    [ (x,y,z) for y in range(10) if y%2==0 for z in range(20) if z%3==0 ... somehow defining x(y,z) ... ]


    I would consider something like this to be more clean, especially since what I really need to do is much more complicated than the example I give here. Everything I have tried has given me a syntax error.

    Continue reading...

Compartilhe esta Página