我有这个:
(([75, 0], [100, 0], [100, 370]), ([75, 0], [100, 370], [75, 370]))
来自此:
[(array([75, 0]), array([100, 0]), array([100, 370])), (array([75, 0]), array([100, 370]), array([ 75, 370]))]
我希望:
[(x1, y1, x2 , y2 ,x3 ,y3), (x1, y1, x2 , y2 ,x3 ,y3), ...]
或
[(75, 0, 100, 0, 100, 370), (75, 0, 100, 0, 100, 370),.....]
感谢您的帮助!
答案 0 :(得分:3)
您可以使用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]
输出:
[[75, 0, 100, 0, 100, 370], [75, 0, 100, 370, 75, 370]]
或在Python2中使用reduce
:
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]
输出:
[[75, 0, 100, 0, 100, 370], [75, 0, 100, 370, 75, 370]]
答案 1 :(得分:2)
您可以使用列表理解:
>>> 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)]
答案 2 :(得分:1)
易于理解的版本:
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)
你会得到:
>>> 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)]
可能有使用列表理解的较短版本,但可读性较差。
答案 3 :(得分:0)
从这个例子开始:
from operator import add
from functools import reduce
reduce(add, (x for x in [[1, 2], [3, 4]]))
输出:
[1,2,3,4]
现在只对元组中的每个元素执行此操作:
[tuple(reduce(add, x)) for x in data]
输出:
[(75,0,100,0,100,370),(75,0,100,370,75,370)]