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!!
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]
L = [
(
e,
(sum(r[2] for r in D if r[0]==e))
)
for e in C
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With