Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List comprehension in python with variable assignment

Suppose i have the following for loop

L=[]
for e in C:
    t=0
    for r in D:
        if r[0]==e:
            t=t+r[2]
    L.append((e,t))

To give some more information e is a list, r is a tuple of size 3. I also want each element of L to contain a tuple.

How do i write the following in a list comprehension? I'm unsure as there are variable assignments in the for loop. I'd really appreciate any help! Thanks!!

like image 344
Iltl Avatar asked Dec 03 '25 09:12

Iltl


2 Answers

work it up in reverse.

What is the data to append to L ? a tuple. What is this tuple made of? e (we have it) and the sum of some terms given a condition.

So without testing I can write:

L = [(e,sum(r[2] for r in D if r[0]==e)) for e in C]
like image 99
Jean-François Fabre Avatar answered Dec 04 '25 22:12

Jean-François Fabre


L = [
    (
        e,
        (sum(r[2] for r in D if r[0]==e))
    )
    for e in C
]
like image 27
Tom Dalton Avatar answered Dec 04 '25 21:12

Tom Dalton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!