Reputation: 25
I have this :
(([75, 0], [100, 0], [100, 370]), ([75, 0], [100, 370], [75, 370]))
that come from this :
[(array([75, 0]), array([100, 0]), array([100, 370])), (array([75, 0]), array([100, 370]), array([ 75, 370]))]
and I want to have :
[(x1, y1, x2 , y2 ,x3 ,y3), (x1, y1, x2 , y2 ,x3 ,y3), ...]
or
[(75, 0, 100, 0, 100, 370), (75, 0, 100, 0, 100, 370),.....]
Thanks for the help!
Upvotes: 2
Views: 77
Reputation: 346
Easy to understand version:
original = (([75, 0], [100, 0], [100, 370]), ([75, 0], [100, 370], [75, 370]))
final = []
for each_tuple in original:
final_child_list = []
for each_list in each_tuple:
final_child_list.extend(each_list)
final.append(final_child_list)
You'll get:
>>> final
[[75, 0, 100, 0, 100, 370], [75, 0, 100, 370, 75, 370]]
# if you prefer the inside element to be tuples
>>> [tuple(x) for x in final]
[(75, 0, 100, 0, 100, 370), (75, 0, 100, 370, 75, 370)]
There might be shorter versions using list comprehension, but less readability.
Upvotes: 0
Reputation: 27251
Starting with this example:
from operator import add
from functools import reduce
reduce(add, (x for x in [[1, 2], [3, 4]]))
Outputs:
[1, 2, 3, 4]
Now just do this for each element in the tuple:
[tuple(reduce(add, x)) for x in data]
Outputs:
[(75, 0, 100, 0, 100, 370), (75, 0, 100, 370, 75, 370)]
Upvotes: 0
Reputation: 11496
You could use a list comprehension:
>>> t = (([75, 0], [100, 0], [100, 370]), ([75, 0], [100, 370], [75, 370]))
>>> [tuple(sub for el in l for sub in el) for l in t]
[(75, 0, 100, 0, 100, 370), (75, 0, 100, 370, 75, 370)]
Upvotes: 2
Reputation: 71471
You can use itertools.chain
:
import itertools
s = (([75, 0], [100, 0], [100, 370]), ([75, 0], [100, 370], [75, 370]))
final_s = [list(itertools.chain.from_iterable(i)) for i in s]
Output:
[[75, 0, 100, 0, 100, 370], [75, 0, 100, 370, 75, 370]]
or using reduce
in Python2:
s = (([75, 0], [100, 0], [100, 370]), ([75, 0], [100, 370], [75, 370]))
new_s = [reduce(lambda x, y:list(x)+list(y), i) for i in s]
Output:
[[75, 0, 100, 0, 100, 370], [75, 0, 100, 370, 75, 370]]
Upvotes: 3