Medo
Medo

Reputation: 1032

Convert list comprehension to traditional approach

I am trying to get myself familiar with list comprehension as much as possible. I have the following pythonic loop:

p = multiprocessing.Pool(processes=multiprocessing.cpu_count())
for result in p.imap_unordered(process_next, [(x1, models, y1) for _ in range(iterations)]):
    # some stuff

I am not sure if it is equivalent to:

p = multiprocessing.Pool(processes=multiprocessing.cpu_count()) 
for result in p:
    p.imap_unordered(process_next, [(x1, models, y1)])
    M = []
    for _ in range(iterations):
        M.append(_)

Kindly, can someone verify my understanding? Thank you

Upvotes: 0

Views: 34

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121594

The list comprehension is one argument to a call to p.imap_unordered(); you'd need to extract it first:

_arg2 = [(x1, models, y1) for _ in range(iterations)]
for result in p.imap_unordered(process_next, _arg2):
    # ...

Now you can expand that into a traditional for loop:

_arg2 = []
for _ in range(iterations):
    _arg2.append((x1, models, y1))
for result in p.imap_unordered(process_next, _arg2):
    # ...

The for result in p.imap_unordered() loop and call are otherwise independent from the list comprehension.

Upvotes: 4

Related Questions