将一系列元组和列表解压缩到一维列表中?

Unpack series of tuples and lists into 1-d list?

我正在尝试从三种列表创建一个数组。喜欢 l1l2l3。我收到错误消息说 float 不可迭代。如何将这些列表解压缩为 python 中的一维列表?

l1=[(260.3, 185.0), (268.01, 499.16)]
l2=[(268.01, 500.87), (678.9, 506.0)]
l3=((149.86, 354.48), (182.39, 344.2))
def unpack_lines(l1, l2, l3):
    out = []
    out.extend(l1[0][0])
    out.extend(l1[0][1])
    out.extend(l1[1][0])
    out.extend(l1[1][1])
    out.extend(l2[0][0])
    out.extend(l2[0][1])
    out.extend(l2[1][0])
    out.extend(l2[1][1])
    out.extend(l3[0][0])
    out.extend(l3[0][1])
    out.extend(l3[1][0])
    out.extend(l3[1][1])
    return out

unpack_lines(l1, l2, l3)

错误


TypeError                                 Traceback (most recent call last)
<ipython-input-27-6f84bf5b956a> in <module>
----> 1 unpack_lines(l1, l2, l3)

<ipython-input-26-159b13d00464> in unpack_lines(l1, l2, l3)
      1 def unpack_lines(l1, l2, l3):
      2     out = []
----> 3     out.extend(l1[0][0])
      4     out.extend(l1[0][1])
      5     out.extend(l1[1][0])

TypeError: 'float' object is not iterable

预期产出

[260.3,
185.0,
 268.01,
 499.16,
 268.01,
 500.87,
 678.9,
 506.0,
 149.86,
 354.48,
 182.39,
 344.2]

您可以只使用 itertools.chain.from_iterable over itertools.chain 个,

>>> list(itertools.chain.from_iterable(itertools.chain(l1, l2, l3)))

注意:如果您需要做的只是遍历值,我会放弃 list 创建,否则没问题。

尽管如此,我看到您正在使用 numpy。然后你可以 flatten 这样的数组,

>>> import numpy as np
>>> 
>>> l1=[(260.3, 185.0), (268.01, 499.16)]
>>> l2=[(268.01, 500.87), (678.9, 506.0)]
>>> l3=((149.86, 354.48), (182.39, 344.2))
>>> 
>>> data = np.array([l1, l2, l3])
>>> data
array([[[260.3 , 185.  ],
        [268.01, 499.16]],

       [[268.01, 500.87],
        [678.9 , 506.  ]],

       [[149.86, 354.48],
        [182.39, 344.2 ]]])

>>> data.flatten()
array([260.3 , 185.  , 268.01, 499.16, 268.01, 500.87, 678.9 , 506.  ,
       149.86, 354.48, 182.39, 344.2 ])
>>> list(_)
[260.3, 185.0, 268.01, 499.16, 268.01, 500.87, 678.9, 506.0, 149.86, 354.48, 182.39, 344.2]

如果您的目标是简单地展平元组列表,您可以使用:

[item for sublist in zip(l1,l2,l3) for tupel in sublist for item in tupel]

Out[4]: 
[260.3,
 185.0,
 268.01,
 500.87,
 149.86,
 354.48,
 268.01,
 499.16,
 678.9,
 506.0,
 182.39,
 344.2]

使用这个递归函数。

def unpack(item):
    result = []
    if item is not None:
        if type(item) in [list, tuple]:
            for element in item:
                result.extend(unpack(element))
        elif type(item) is float:
            for elemtn in item:
                result.append(item)
    return result 
l1=[(260.3, 185.0), (268.01, 499.16)]
l2=[(268.01, 500.87), (678.9, 506.0)]
l3=((149.86, 354.48), (182.39, 344.2))
result = unpack(l1)+unpack(l2)+unpack(l3)