1

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])
1
  • 2
    Have you tried anything yet? Commented Apr 15, 2019 at 23:16

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.