a = [(0,0,0), (0,1,1), (1,0,1), (1,1,0)] b = [0, 2, 1, 1, 2, 2] x = 0 for index in b: x += a[index] print(x)
Which shortens to:
x = sum(a[index] for index in b)
Explanation of first method:
- create a variable to hold current sum
- for each index number specified in
b, do the following:
a[index]to the sum
So on each loop cycle,
sum method, those cycles are added together as the function takes the generator expression and exhausts it.
N Chauhan posted this
Have an answer?