2017-08-13 148 views

回答

2

我想你需要转换为数组,然后再由ravel和最后转换压扁到list:由chain.from_iterable

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

与flattenting另一种解决方案:

from itertools import chain 

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

我发现,实现代码我的请求: x = [str(i [0])for the_list]

+0

有必要转换为'str'? – jezrael

0

一个很好的普通p用'扁平'列表的内部数组(或对象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'] 

我不得不因为我包括一个0D阵列使用hstack;如果他们都是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']