Python将元组转换为数组

时间:2013-12-17 15:23:11

标签: python list

如何将三维元组转换为数组

a = []
a.append((1,2,4))
a.append((2,3,4))

在数组中:

b = [1,2,4,2,3,4]

3 个答案:

答案 0 :(得分:29)

使用list comprehension

>>> a = []
>>> a.append((1,2,4))
>>> a.append((2,3,4))
>>> [x for xs in a for x in xs]
[1, 2, 4, 2, 3, 4]

使用itertools.chain.from_iterable

>>> import itertools
>>> list(itertools.chain.from_iterable(a))
[1, 2, 4, 2, 3, 4]

答案 1 :(得分:10)

简单的方法,使用extend方法。

x = []
for item in a:
    x.extend(item)

答案 2 :(得分:4)

如果你的意思是数组在numpy数组中,你也可以这样做:

a = []
a.append((1,2,4))
a.append((2,3,4))
a = np.array(a)
a.flatten()