2

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]]
N Chauhan
  • 3,407
  • 2
  • 7
  • 21

6 Answers6

2

You would/could normally use this expression will do what you want:

sum(a[x] for x in b)

But in your case the elements of a of tuples, and you will get an error if you try this. You need to make a list of the tuples, then use chain from itertools to flatten it.

from itertools import chain

foo = [a[x] for x in b]
x = chain(*foo)

Or:

x = tuple(chain(*a[x] for x in b))
Batman
  • 8,571
  • 7
  • 41
  • 80
2

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)

Or generator:

print(sum((a[x] for x in b),()))

Also outputs:

(0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1)
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
1

Try this:

a = [(0,0,0), (0,1,1), (1,0,1), (1,1,0)]
b = [0, 2, 1, 1, 2, 2]
x = []
for index in b:
    x += list(a[index])

x = tuple(x)

print(x)

Which shortens to:

x = tuple(sum(list(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.

N Chauhan
  • 3,407
  • 2
  • 7
  • 21
1

Reduce approach.

from functools import reduce
x = reduce(lambda p, q: p + q, [a[i] for i in b])
0
tuple(q for i in b for q in a[i])

here the first loop loops through b and then through the corospondent a index to the b value, in which here becomes the q and thus the generator is created, as for the tuple(), it's purpose is that comprehensions are generator and can be put in to array like object, tuples however have none, the parenthasies that just ther, the real tuple is defined by the commas but the generator doesn't have those so i have to explicitly tell it that i want a tuple.

Jonas Wolff
  • 2,034
  • 1
  • 12
  • 17
  • Why? While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Nic3500 Sep 16 '18 at 03:32
0

Do you mean like this?

x = 0
for sub_b in b:
    x = x + a[sub_b]
toom501
  • 324
  • 1
  • 3
  • 15