How to convert a list of ndarray arrays into list in python

时间:2017-08-13 13:57:49

标签: python list numpy

I have a list of ten 1-dimension-ndarrays, where each on hold a string, and I would like to one long list where every item will be a string (without using ndarrays anymore). How should I implement it?

3 个答案:

答案 0 :(得分:2)

I think you need convert to array first, then flatten by ravel and last convert to list:

a = [np.array([x]) for x in list('abcdefghij')]
print (a)
[array(['a'],
      dtype='<U1'), array(['b'],
      dtype='<U1'), array(['c'],
      dtype='<U1'), array(['d'],
      dtype='<U1'), array(['e'],
      dtype='<U1'), array(['f'],
      dtype='<U1'), array(['g'],
      dtype='<U1'), array(['h'],
      dtype='<U1'), array(['i'],
      dtype='<U1'), array(['j'],
      dtype='<U1')]

b = np.array(a).ravel().tolist()
print (b)
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

Another solution with flattenting by chain.from_iterable:

from  itertools import chain

b = list(chain.from_iterable(a))
print (b)
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

答案 1 :(得分:0)

我找到了完成我的请求的代码:     x = [str(i [0])for the in the_list]

答案 2 :(得分:0)

一种很好的通用方式“扁平化”&#39;列出的内部数组(或对象dtype数组数组)是使用concatenate函数之一。

例如,包含不同长度的数组的列表,包括0d):

In [600]: ll = [np.array('one'), np.array(['two','three']),np.array(['four'])]
In [601]: ll
Out[601]: 
[array('one',
       dtype='<U3'), array(['two', 'three'],
       dtype='<U5'), array(['four'],
       dtype='<U4')]
In [602]: np.hstack(ll).tolist()
Out[602]: ['one', 'two', 'three', 'four']
In [603]: np.hstack(ll).tolist()
Out[603]: ['one', 'two', 'three', 'four']

我不得不使用hstack,因为我包含了一个0d数组;如果他们都是1d concatenate就足够了。

如果数组都包含一个字符串,那么其他解决方案都可以正常工作

In [608]: ll = [np.array(['one']), np.array(['two']),np.array(['three']),np.array(['four'])]
In [609]: ll
Out[609]: 
[array(['one'],
       dtype='<U3'), array(['two'],
       dtype='<U3'), array(['three'],
       dtype='<U5'), array(['four'],
       dtype='<U4')]

In [610]: np.hstack(ll).tolist()
Out[610]: ['one', 'two', 'three', 'four']

In [611]: np.array(ll)
Out[611]: 
array([['one'],
       ['two'],
       ['three'],
       ['four']],
      dtype='<U5')  # a 2d array which can be raveled to 1d

In [612]: [i[0] for i in ll]         # extracting the one element from each array
Out[612]: ['one', 'two', 'three', 'four']