pietà
pietà

Reputation: 770

Pythonic way to combine two FOR loops and an IF statement?

I have this loop:

for e in elements:
    for h in hs:
        if h.complete and e.date < h.date:
            print('----completed at time----',)

Is there a way to write it in one line or in a Pythonic way?

Upvotes: 2

Views: 2786

Answers (2)

Tedil
Tedil

Reputation: 1933

There's a plethora of different ways to shrink this to fewer lines -- but most of them will be less readable. For example:

  • not-really-list comprehension: [print('whatever') for e in elements for h in hs if e.date < h.date]

  • list comprehension: for p in [sth(e, h) for e in elements for h in hs if e.date < h.date]: print(p)

  • using itertools.product:

    for e, h in product(elements, hs):
        if h.complete and e.date < h.date:
            print('whatever')
    
  • same as above but with filter:

    for e, h in filter(lambda e, h: h.complete and e.date < h.date, product(elements, hs)):
        print('whatever')
    

Edit: My personal preference lies with the first product example, which (while only shaving a single line off of the original code) is better at telegraphing what the code actually does.

Upvotes: 3

wim
wim

Reputation: 362517

Is there a way to write it in one line

Yes.

or in a Pythonic way?

What you have currently is already the most Pythonic way, no need to change anything here.

Upvotes: 3

Related Questions