Sum of many lists

1688 views
6

How to simplify the assignment to `x` (probably using a loop of some kind) in the following?

``````a = [(0,0,0), (0,1,1), (1,0,1), (1,1,0)]
b = [0, 2, 1, 1, 2, 2]
x = a[b[0]] + a[b[1]] + a[b[2]] + a[b[3]] + a[b[4]] + a[b[5]]
``````

im confused, your code works.

@d_kennetz he want's to simplify it

6

Try this:

``````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:
• add `a[index]` to the sum

So on each loop cycle, `a[index]` becomes `a[0]`, `a[2]`, `a[1]` ... `a[2]`

In the `sum` method, those cycles are added together as the function takes the generator expression and exhausts it.

posted this
11

Do you mean like this?

``````x = 0
for sub_b in b:
x = x + a[sub_b]
``````

posted this
10

This expression will do what you want:

``````sum(a[x] for x in b)
``````

posted this
6

Try this, need second argument for `sum`:

``````print(sum(map(lambda x: a[x],b),()))
``````

Output:

``````(0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1)
``````

posted this