InstantNut
InstantNut

Reputation: 93

Convert single 'for' loop into nested 'for' loop

I was wondering how could I convert this for loop into a multiple line version!

(str(s) for s in [sum(float(q) for q in e) for e in more_hours])

Upvotes: 1

Views: 65

Answers (2)

behold
behold

Reputation: 556

your example outputs a generator object. If you're just looking to generate equivalent content (and not a generator object), following output1 and output2 prints same output:

more_hours = [[1.,2.],[3.,4.]]

b = (str(s) for s in [sum(float(q) for q in e) for e in more_hours])

# output 1
for s in b:
    print(s)

# output 2
for e in more_hours:
    val = 0
    for q in e:
        val = val + float(q)
    print(val)

Upvotes: 0

blhsing
blhsing

Reputation: 107124

Enclosed in parentheses, this is a generator expression equivalent to the following generator:

def generator():
    for e in more_hours:
        yield str(sum(float(q) for q in e))

or with the inner generator expression further broken down:

def generator():
    for e in more_hours:
        s = 0
        for q in e:
            s += float(q)
        yield str(s)

Upvotes: 1

Related Questions