簡體   English   中英

Python列表到元組

[英]Python list to tuple

我有這個 :

(([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),.....]

謝謝您的幫助!

您可以使用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]]

或使用reduce在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]

輸出:

[[75, 0, 100, 0, 100, 370], [75, 0, 100, 370, 75, 370]]

您可以使用列表理解:

>>> 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)]

易於理解的版本:

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)]

使用列表理解的版本可能更短,但可讀性較低。

從此示例開始:

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)]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM