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]]
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]]
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))
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)
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:
b
, do the following:
a[index]
to the sumSo 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.
Reduce approach.
from functools import reduce
x = reduce(lambda p, q: p + q, [a[i] for i in b])
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.